在Mongodb中更新多嵌套数组 [英] Update multi nested array in Mongodb

查看:65
本文介绍了在Mongodb中更新多嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Mongodb中有一个文档架构,如下所示:

I have a document schema in Mongodb that looks like this:

{
    _id: 1
    tags: [{
        tag: 'foo'
        links: [{
            link: 'http:www.google.com'
            date: '123'
        }] 
    }]
}

我正在尝试将链接推送到文档唯一的'links'数组中.

I am trying to push a link into the 'links' array that will be unique to the document.

我的第一个查询...

My first query...

db.userlinks.update (
    {_id: 1, tags: {$nin: [{tag:'foo'}]}}, 
    {$push: {'tags': {tag:'foo'}}}, 
    {upsert: true}
)

请给我(如果标签不存在,则创建标签)

Gives me this (creates the tag if it doesn't exist)

{ "_id" : 1, "tags" : [ { "tag" : "foo" } ] }

然后我继续执行此查询...

I then follow that up with this query...

db.userlinks.update (
    {_id: 1, tags: {tag: 'foo', links: {$nin: [{link: 'http://www.google.com'}]}}}, 
    {$push: {tags: {tag: 'foo', links: {link: 'http://www.google.com', date: '123'}}}}, 
    {upsert: true}
)

但是我收到此错误:无法将$ push/$ pushAll修饰符应用于非数组"

But I get this error: "Cannot apply $push/$pushAll modifier to non-array"

我很确定问题出在第二个查询的更新"组件中,但是我不确定如何解决它.任何帮助将不胜感激.

I'm pretty sure the problem is in the 'update' component of my second query, but I'm not sure how to fix it. Any help would be appreciated.

现在我的第一个查询...(感谢乔)

My first query is now... (thanks to Joe)

db.userlinks.update (
    {_id: 1, tags: {$nin: [{tag:'foo'}]}}, 
    {$push: {'tags': {tag:'foo', links:[]}}}, 
    {upsert: true}
)

现在我的第二个查询...

My second query is now...

db.userlinks.update (
    {_id: 1, 'tags.tag': 'foo'}, 
    {$push: {'tags.$.links': {link: 'http://www.google.com', date: '123'} } }
)

成功将链接推入'links'数组,但是它也允许重复.我不允许重复的链接. $ addToSet可以工作,但是如果日期更改,则仍会插入重复的链接.

Which successfully pushes the link into the 'links' array, however it also allows duplicates. I can't allow duplicate links. $addToSet kind of works, however if the date changes, then it still inserts a duplicate link.

有没有一种方法可以检查第二个查询的查询"部分中是否存在链接,或者仅在某些字段匹配时才使用addToSet?

Is there a way to either check for the existence of the link in the 'query' part of my second query, or instead only addToSet if certain fields match?

推荐答案

我终于明白了...尽管任何人都可以找到一种更好的方法,请将其添加为答案.

I finally got it... although if anyone can see a better way to do this, please add it as an answer.

// create the userlinks collection if it doesn't exist
// also add a tag 'foo' into it, but only if the tag doesn't exist
db.userlinks.update (
    {_id: '1', 'tags.tag': {$nin: ['foo']}}, 
    {$push: {'tags': {tag:'foo', links:[]}}},
    {upsert: true}
)

// add a link into the 'foo' tag, but only if the link doesn't exist
db.userlinks.update(
    {_id: '1', 'tags.tag': 'foo', 'tags.links.link': {$nin: ['http://foobar.com']}},
    {$push: {'tags.$.links': {link: 'http://foobar.com', date: '15'} } }
)

这篇关于在Mongodb中更新多嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆