Update multi nested array in Mongodb

前端 未结 2 867
醉酒成梦
醉酒成梦 2021-01-17 10:03

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

{
    _id: 1
    tags: [{
        tag: \'foo\'
        links: [{
            link: \'http:www.googl         


        
2条回答
  •  情话喂你
    2021-01-17 10:24

    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'} } }
    )
    

提交回复
热议问题