更新Mongodb中的多嵌套数组

16 mongodb

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

{
    _id: 1
    tags: [{
        tag: 'foo'
        links: [{
            link: 'http:www.google.com'
            date: '123'
        }] 
    }]
}
Run Code Online (Sandbox Code Playgroud)

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

我的第一个询问......

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

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

{ "_id" : 1, "tags" : [ { "tag" : "foo" } ] }
Run Code Online (Sandbox Code Playgroud)

然后我用这个查询来跟进...

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}
)
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:"无法将$ push/$ pushAll修饰符应用于非数组"

我很确定问题出在我的第二个查询的'update'组件中,​​但我不确定如何修复它.任何帮助,将不胜感激.

编辑

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

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

我的第二个问题是......

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

它成功地将链接推送到'链接'数组,但它也允许重复.我不能允许重复链接.$ addToSet类型有效,但是如果日期发生变化,那么它仍会插入重复的链接.

有没有办法检查我的第二个查询的"查询"部分中是否存在链接,或者只检查某些字段匹配时是否添加addToSet?

小智 18

我终于明白了......虽然如果有人能看到更好的方法来做到这一点,请添加它作为答案.

// 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'} } }
)
Run Code Online (Sandbox Code Playgroud)