MongoDB:子数组的Update属性仅更新第一个元素 [英] MongoDB: Update property of subarray just updates the first element
问题描述
匹配元素如下所示:
{
"_id": {
"$oid": "519ebd1cef1fce06f90e3157"
},
"from": "Tester2",
"to": "Tester",
"messages": [
{
"username": "Tester2",
"message": "heeey",
"read": false
},
{
"username": "Tester",
"message": "hi!",
"read": false
},
{
"username": "Tester2",
"message": "test",
"read": false
}
],
}
现在,我尝试将用户名不等于Tester
的子元素的read
属性设置为当前日期:
Now I try to set the read
property to the current date just of the subelements where the username is not equal to Tester
:
var messages = db.collection('messages');
messages.update(
{
_id: new BSON.ObjectID("519ebd1cef1fce06f90e3157"),
messages: {
$elemMatch: { username: { $ne: "Tester" } }
}
},
{ $set: { 'messages.$.read': new Date() } },
{ multi: true }, function(error, result) {
console.log(error);
console.log(result);
});
但是只有第一个消息子元素read
属性会更新:
But just the first messages subelement read
property updates:
{
"_id": {
"$oid": "519ebd1cef1fce06f90e3157"
},
"from": "Tester2",
"to": "Tester",
"messages": [
{
"username": "Tester2",
"message": "heeey",
"read": {
"$date": "2013-01-01T00:00:00.000Z"
}
},
{
"username": "Tester",
"message": "hi!",
"read": false
},
{
"username": "Tester2",
"message": "test",
"read": false
}
],
}
代码有什么问题? 我正在使用node.js v0.10.8和MongoDB v2.4.3以及 node-mongodb-native .
What's wrong with the code? I'm using node.js v0.10.8 and MongoDB v2.4.3 together with node-mongodb-native.
推荐答案
您的代码没有任何问题. $
运算符包含第一个匹配数组元素. {multi: true}
选项仅使update
适用于多个文档,而不适用于数组元素.要在单个update
中更新多个数组元素,必须通过数字索引指定它们.
There's nothing wrong with your code; the $
operator contains the index of the first matching array element. The {multi: true}
option only makes the update
apply to multiple documents, not array elements. To update multiple array elements in a single update
you must specify them by numeric index.
因此,您必须执行以下操作:
So you'd have to do something like this:
messages.update(
{
_id: new BSON.ObjectID("519ebd1cef1fce06f90e3157")
},
{ $set: {
'messages.0.read': new Date(),
'messages.2.read': new Date()
} },
function (err, result) { ... }
);
这篇关于MongoDB:子数组的Update属性仅更新第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!