How to insert an element to MongoDB internal list?

后端 未结 2 1764
时光说笑
时光说笑 2020-11-29 01:16

I have the following doc stored in MongoDB:

{
    name: \'myDoc\',
    list: [
        {
            id:1
            items:[
                {id:1, name:\'i         


        
相关标签:
2条回答
  • 2020-11-29 01:58

    You can use this: -

    > var toInsert = {id: 5, name: 'item6'}
    > db.abc.update(
                { name: 'myDoc', list: { $elemMatch: { id: 2 } } },
                { $addToSet: { 'list.$.items': toInsert } }
      )
    

    The query part will find the document from the list array with id = 2. Then we use $ positional element to add a new element at that array index.

    See positional $ operator


    You can also replace list: {$elemMatch: {id: 2}} with just 'list.id': 2.

    But using $elemMatch will be better, when you want to update based on multiple elements of your array. For e.g., when your matching criteria is id and some another field in the array say length: -

    list: {$elemMatch: {id: 2, length: 5}}
    
    0 讨论(0)
  • 2020-11-29 02:03

    One way of doing it would be with $push:

    db.col.update(
        { name: 'doc', 'list.id': 2 }, 
        {$push: {'list.$.items': {id: 5, name: 'item5'}}}
    )
    

    http://docs.mongodb.org/manual/reference/operator/push/

    You can also replace $push with other operators like (possibly) $addToSet to get the exact results you are looking for.

    0 讨论(0)
提交回复
热议问题