mongodb更新指定条件的子文档

文档内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"_id": ObjectId("5689db252d162c9881532986"),
"openid": "xialei",
"channels": [
{
"channel_id": "c1"
},
{
"channel_id": "c2"
},
{
"channel_id": "c2"
},
{
"channel_id": "c2"
}
]
}

需求

把该文档的channels中channel_id为c2的删除,但是主记录要保留。
这时候就不能用remove方法了,该方法会删除整条文档,查询官方文档发现有个findAndModify方法。

函数原型

1
2
3
4
5
6
7
8
9
10
db.collection.findAndModify({
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>
bypassDocumentValidation: <boolean>
});
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×