How to write this MongoDb update operator

给你一囗甜甜゛ 提交于 2019-12-12 03:34:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!