问题
I have an 'applications' collection in the following form:
{
"_id" : "<id>",
"versions" : {
"2_2_1" : 5,
"2_2_2" : 38,
"2_2_3" : 76
}
}
I want to increment the version number based on the version of application that sends a request. How can I write the $inc operator for my update query?
I can't seem to get my query working because the incremented version number can always vary from request to request. I can't get the positional $ operator working correctly for my query.
回答1:
You use "dot notation" in order to access the specifc value under "version", but also you are going to have to "build" the object key by whatever language you are using.
As a JavaScript example:
var request = "2_2_1";
var update = { "$inc": { } };
update["$inc"]["versions." + request] = 1;
This yields:
{ "$inc": { "versions.2_2_1": 1 } }
So you just perform the update:
db.collection.update({ "_id": id },update);
If that "request" version sub-key exists then it is "incremented" from it's previous value. If it is a "new" key then the initial value will be 1
.
来源:https://stackoverflow.com/questions/31200351/how-to-write-this-mongodb-update-operator