我有以下文档(我正在使用Microsoft的Azure Cosmos for MongoDB)
db.polls.find({ _id: ObjectId("59ee64038c3a482200a08dbc")})
{
"_id" : ObjectId("59ee64038c3a482200a08dbc"),
"title" : "Lunch Games",
"options" : [
{
"_id" : ObjectId("59ee64038c3a482200a08dbd"),
"text" : "7 Wonders",
"votes" : 1
},
{
"_id" : ObjectId("59ee64038c3a482200a08dbe"),
"text" : "Acquire",
"votes" : 0
},
{
"_id" : ObjectId("59ee66fa99ea5912bc483cc1"),
"text" : "Testing 1234",
"votes" : 1
}
],
"__v" : 1
}
我希望做的是通过findOneAndUpdate
调用增加投票整数。我试图使用的电话是
db.polls.findOnAndUpdate({
_id: ObjectId("59ee64038c3a482200a08dbc"),
"options.text" : "7 Wonders"
},
{
$inc : {'options.$.votes' : 1}
});
根据我对$
位置运算符的理解,它将选择与查询的查找部分匹配的第一个项目,并对该元素执行操作。我从应用程序收到的是以下异常
MongoError: Invalid BSON field name 'options.$.votes'
at Function.MongoError.create (D:\home\site\wwwroot\node_modules\mongodb-core\lib\error.js:31:11)
at D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\pool.js:497:72
at authenticateStragglers (D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\pool.js:443:16)
at Connection.messageHandler (D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\pool.js:477:5)
at TLSSocket.<anonymous> (D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\connection.js:331:22)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
at TLSWrap.onread (net.js:548:20)
当我用$
替换0
时,查询成功并更新第一项的投票。