How to insert an element to MongoDB internal list?

后端 未结 2 1784
时光说笑
时光说笑 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 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.

提交回复
热议问题