Update multi nested array in Mongodb

前端 未结 2 858
醉酒成梦
醉酒成梦 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:20

    Perhaps change your first query to:

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

    The $push operation should only affect links, not the tag.

    {$push: {'tags.links': {link: 'http://www.google.com', date: '123'} } },
    
    0 讨论(0)
  • 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'} } }
    )
    
    0 讨论(0)
提交回复
热议问题