如何编写此MongoDb更新运算符 [英] How to write this MongoDb update operator

查看:67
本文介绍了如何编写此MongoDb更新运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的应用程序"集合:

I have an 'applications' collection in the following form:

{ 
  "_id" : "<id>", 
  "versions" : {
      "2_2_1" : 5, 
      "2_2_2" : 38, 
      "2_2_3" : 76
  }
}

我想根据发送请求的应用程序的版本来增加版本号.如何为更新查询编写$ inc运算符?

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.

推荐答案

您使用点符号" 来访问版本"下的特定值,但您还必须使用任何使用的语言来构建"对象键.

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.

以JavaScript为例:

As a JavaScript example:

var request = "2_2_1";
var update = { "$inc": { } };

update["$inc"]["versions." + request] = 1;

这将产生:

{ "$inc": { "versions.2_2_1": 1 } }

因此,您只需执行更新:

So you just perform the update:

db.collection.update({ "_id": id },update);

如果该请求"版本子键存在,那么它将从其先前值递增".如果它是新"键,则初始值为1.

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.

这篇关于如何编写此MongoDb更新运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆