Arrays 在mongodb中更新数组中的多个元素
我在mongodb的股票收藏中有如下文档Arrays 在mongodb中更新数组中的多个元素,arrays,mongodb,mongodb-query,Arrays,Mongodb,Mongodb Query,我在mongodb的股票收藏中有如下文档 { _id: 'xRMuRBhqRLgASyQyW', History: [ { orderId: '12032017001877', status: 'COMPLETED', }, { orderId: '22122017002450', status: 'PROCESSED', }, { orderId: '22122018002450'
{ _id: 'xRMuRBhqRLgASyQyW',
History:
[ { orderId: '12032017001877',
status: 'COMPLETED',
},
{ orderId: '22122017002450',
status: 'PROCESSED',
},
{ orderId: '22122018002450',
status: 'DEPOSIT',
}
]
}
我想遍历
stocks
集合中的所有文档,如果状态不是“已处理”
,则添加一个字段标志:true
只需使用“$”运算符即可。比如:
db.stocks.update( {"history.status" : { $not: "PROCESSED" } ,
{ $set: {"history.$.flag": true }} ,
false ,
true);
您需要使用all操作符来更新数组中的每个元素
db.collection.update(
{ "History": { "$elemMatch": { "status": { "$ne": "PROCESSED" } } } },
{ "$set": { "History.$[].flag": false } },
{ "multi": true }
)
您可以使用脚本来实现它
db.stocks.find().forEach(function (e) {
var modified = false;
e.History.forEach(function (o) {
if (o.status != "PROCESSED") {
o.flag = true;
modified = true;
}
});
if (modified) {
db.stocks.save(e);
}
});
我的答案非常相似,但是 添加了两个额外的参数(用于
upsert
和multi
)。作为参考,您可以查看
如果每个数组中只有一个子文档,则可以使用mongodb位置运算符$。如果有多个,那么您很可能必须阅读文档,在客户端上更改其内容,然后保存(可能是一系列的
$set
命令,如$set:{'History.2.flag':'true'}
)Sergio Tulentsev,先生,您是在谈论历史数组吗?不,该数组中有许多项。我正在尝试使用mongo shell更改我的数据库,因此没有客户端。mongo shell是客户端。不,先生,我正在使用Nosqlbooster@AnthonyWinzlet:噢,(对我来说)这是新的。谢谢,TIL。在同一个数组中不适用于多个匹配项。先生,这是一个不错的匹配项,但我认为应该为“upsert”和“multi”添加两个额外的参数(基本上是false和true,因为它们适合我)。我之所以在这里写作,是因为“multi”可以更改多个文档。您可以对多个文档使用multi
true,但不知道为什么在这里插入upsert
?先生,使用“upser”将其改为false,我们可以确保即使没有任何文档满足标准,也不会创建新文档dbingo!!这是更新数组中每个元素的完美答案。P E R F E C TI发现这是最好的。最适合我的问题
db.stocks.update(
{ "History": { "$elemMatch": { "status": { "$ne": "PROCESSED" } } } },
{ "$set": { "History.$[].flag": false }},
false, // show that if there is not any document with specified criteria , it will not create a new document.
ture // according to document of mongodb if multi is true then more than one document will be updated, other wise only one document will be updated.
)