node.js mongodb 只更新数组中第一个找到的子文档
node.js mongodb only update first found subdocument in array
一个用户集合:
{
"_id" : ObjectId("5785d10570d6c39923d476cf"),
"name" : "BB Cafe",
"transaction" : [
{
"id" : "m69bkn",
"type" : "TYPE1",
"amount" : 0,
},
{
"id" : "nhaa94",
"type" : "TYPE1",
"amount" : 0,
}
]
}
更新声明
var mongodbObjectID = require('mongodb').ObjectID;
db.collection('user').update(
{_id:new mongodb.ObjectID("5785d10570d6c39923d476cf"),
"transaction.amount":0,
"transaction.type":"TYPE1",
"transaction.id":"nhaa94"
}, {$set:{"transaction.$.amount":0.6}}, {w:1}, function(err, resultUpdate) {
}
它更新为 transaction.id = "m69bkn"
而不是 "nhaa94"
我猜它只是更新了第一个找到的子文档
我一直在这里搜索
update array with $ is not working in mongodb-native nodejs
和
https://docs.mongodb.com/manual/reference/operator/update/positional/
和
Updating an array item using NodeJS, MongoDB & Monk
尝试使用 $elemMatch 运算符
来使用这样的查询
{
_id: ObjectId("5785d10570d6c39923d476cf"),
"transaction": {
"$elemMatch": {
"amount": 0,
"type": "TYPE1",
"id": "nhaa94"
}
}
一个用户集合:
{
"_id" : ObjectId("5785d10570d6c39923d476cf"),
"name" : "BB Cafe",
"transaction" : [
{
"id" : "m69bkn",
"type" : "TYPE1",
"amount" : 0,
},
{
"id" : "nhaa94",
"type" : "TYPE1",
"amount" : 0,
}
]
}
更新声明
var mongodbObjectID = require('mongodb').ObjectID;
db.collection('user').update(
{_id:new mongodb.ObjectID("5785d10570d6c39923d476cf"),
"transaction.amount":0,
"transaction.type":"TYPE1",
"transaction.id":"nhaa94"
}, {$set:{"transaction.$.amount":0.6}}, {w:1}, function(err, resultUpdate) {
}
它更新为 transaction.id = "m69bkn"
而不是 "nhaa94"
我猜它只是更新了第一个找到的子文档
我一直在这里搜索
update array with $ is not working in mongodb-native nodejs
和
https://docs.mongodb.com/manual/reference/operator/update/positional/
和
Updating an array item using NodeJS, MongoDB & Monk
尝试使用 $elemMatch 运算符
来使用这样的查询{
_id: ObjectId("5785d10570d6c39923d476cf"),
"transaction": {
"$elemMatch": {
"amount": 0,
"type": "TYPE1",
"id": "nhaa94"
}
}