{
"_id" : ObjectId("52fb2ceb1e2f8622d4228a7a"),
"from" : 0,
"message" : [{
"data" : "test1",
"status" : true,
"time" : 1
}, {
"data" : "test2",
"status" : true,
"time" : 2
}],
"to" : 1,
"type" : "s"
}
如何用一条命令把message数组中2个对象元素中的status属性都改成false?
是否只能在客户端做逻辑处理:
var cursor = db.msg.find({“to”: uid, “message.status”: false});
while(cursor.hasNext()){ //由于默认情况下find取得的游标已经做过快照,所以理论上不会影响在find之后新增的数据
var doc = cursor.next();
var from = doc.from;
var type = doc.type;
//循环对应文档的message数组中的所有元素,进行逐行更改
item.message.foreach(function(msg){
db.msg.update({
“to”: uid,
“from”: from,
“type”: type,
“message.time”: msg.time
},
{
“$set”: {
“message.$.status”: true
}
}
);
});
}
请大家指正~~
You can also change it in the mongo shell.
I also encountered a similar problem. I checked the official documentation. My local solution is as above. I hope it can help you
Use the aggregation framework aggregate to do it. Unwind it first with unwind. Then update all status.
This can be done, mongodb provides a dollar sign "$" to update embedded data objects.
If you want the result, you can write the following statement:
But please note that your update conditional statement must include the condition of the object in the data. For example, {"messaage.status":true} above, you can also change it to something else.
Please refer to the mongodb documentation: http://docs.mongodb.org/manual/reference/operator/update/positional/#update-documents-in-an-array