如何在MongoDB内部列表中插入一个元素? [英] How to insert an element to MongoDB internal list?
本文介绍了如何在MongoDB内部列表中插入一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 MongoDB 中存储了以下文档:
I have the following doc stored in 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'}
]
}
]
}
我找到了一种使用 $addToSet
将元素添加到列表"的方法,但我找不到将某个项目添加到特定项目"列表的方法.
I found a way to add an element to 'list' using $addToSet
but I couldn't find a way to add to a specific list of 'items' an item.
例如我得到以下信息:
{id:5, name:'item5'}
我想将它添加到列表中 id:2 的元素项中.
and I want to add it to the element's item in the list with id:2.
推荐答案
一种方法是使用 $push
:
db.col.update(
{ name: 'doc', 'list.id': 2 },
{$push: {'list.$.items': {id: 5, name: 'item5'}}}
)
http://docs.mongodb.org/manual/reference/operator/push/
您还可以将 $push
替换为其他运算符,例如(可能)$addToSet
以获得您正在寻找的确切结果.
You can also replace $push
with other operators like (possibly) $addToSet
to get the exact results you are looking for.
这篇关于如何在MongoDB内部列表中插入一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文