默认情况下,mongodb update 命令只会更新一个文档。
db.collection.update({document to be found},{changes to be done})
要更新多个文档,您应该包含 multi 关键字。
db.collection.update({document to be found},{changes to be done},{multi:true})
假设您的文档结构如下:
{
"_id": 5,
"body": "Correct horse battery staple",
"comments": [{"user_id": "123"},{"user_id": "456"},{"user_id": "123"}]
}
{
"_id": 6,
"body": "Correct horse battery staple",
"comments": [{"user_id': "23"},{"user_id": "123"},{"user_id": "13"}]
}
在这种情况下,我可能需要更新数组中的多个元素以及多个文档。没有默认的 mongodb 查询来执行此操作。
相反,我将遍历文档并按如下方式执行。
// loop until all documents has been updated
while(db.post.find({'comments.user_id':'123'}).count()!=0)
{
db.post.update(
{ 'comments.user_id':'123' },
{ $set:{'comments.$.user_id':'abc'} },
{ multi:true }
)
}
第一次循环运行后,post collection 将如下所示:
{
"_id": 5,
"body": "Correct horse battery staple",
"comments": [{"user_id": "abc"},{"user_id": "456"},{"user_id": "123"}]
}
{
"_id": 6,
"body": "Correct horse battery staple",
"comments": [{"user_id": "23"},{"user_id": "abc"},{"user_id": "13"}]
}
第二次循环运行后,post collection 将如下所示:
{
"_id": 5,
"body": "Correct horse battery staple",
"comments": [{"user_id": "abc"},{"user_id": "456"},{"user_id": "abc"}]
}
{
"_id": 6,
"body": "Correct horse battery staple",
"comments": [{"user_id": "23"},{"user_id": "abc"},{"user_id": "13"}]
}
在第三次循环运行中,循环终止。