mongodb 如何在MongoDB内部列表中插入一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13987365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:58:58  来源:igfitidea点击:

How to insert an element to MongoDB internal list?

mongodbmongodb-query

提问by Guy Korland

I have the following doc stored in MongoDB:

我在 MongoDB 中存储了以下文档:

{
    name: 'myDoc',
    list: [
        {
            id:1
            items:[
                {id:1, name:'item1'},
                {id:2, name:'item2'}
            ]
        },
        {
            id:2
            items:[
                {id:1, name:'item1'},
                {id:3, name:'item3'}
            ]
        }
    ]
}

I found a way to add an element to 'list' using $addToSetbut I couldn't find a way to add to a specific list of 'items' an item.

我找到了一种将元素添加到“列表”的方法,$addToSet但我找不到将一个项目添加到“项目”的特定列表的方法。

e.g. I get the following:

例如,我得到以下信息:

{id:5, name:'item5'} 

and I want to add it to the element's item in the list with id:2.

我想将它添加到列表中带有 id:2 的元素项中。

回答by Sammaye

One way of doing it would be with $push:

一种方法是使用$push

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

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

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

You can also replace $pushwith other operators like (possibly) $addToSetto get the exact results you are looking for.

您还可以替换$push为其他运算符(如(可能))$addToSet以获得您正在寻找的确切结果。

回答by Rohit Jain

You can use this: -

你可以使用这个: -

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

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

query部分将从list数组中找到文档id = 2。然后我们使用$位置元素在该数组索引处添加一个新元素。

See positional $ operator

positional $ operator



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

您也可以list: {$elemMatch: {id: 2}}仅替换为'list.id': 2.

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

但是$elemMatch当您想根据数组的多个元素进行更新时,使用会更好。例如,当您的匹配条件是id并且数组中的另一个字段表示length:-

list: {$elemMatch: {id: 2, length: 5}}