javascript - How can I use variables as part of field names in the MongoDB shell? - Stack Overflow

How can I use variables as part of field names in the mongodb shell? I am trying to do the following:&g

How can I use variables as part of field names in the mongodb shell? I am trying to do the following:

> var site = "google";
> var y = 10;
> var m = 5;

// This fails (field names as concatenation):
> db.test.update({ "domain" : site},
      { $inc : {"counts.year."+y : 1, "counts.month."+m : 1}}, upsert=true);

> Thu Apr 19 19:12:56 SyntaxError: missing : after property id (shell):1

// This works:
> db.test.update({ "domain" : site}, { $inc : {"counts.year.10" : 1,
      "counts.month.5" : 1}}, upsert=true);

I guess the problem is in the way the JS object is created: for instance var t = 10; doc = {t : 0}; works but var t = 10; doc = {"Test."+t : 0}; does not. How can I work around this?

Thank you,

/David

How can I use variables as part of field names in the mongodb shell? I am trying to do the following:

> var site = "google.";
> var y = 10;
> var m = 5;

// This fails (field names as concatenation):
> db.test.update({ "domain" : site},
      { $inc : {"counts.year."+y : 1, "counts.month."+m : 1}}, upsert=true);

> Thu Apr 19 19:12:56 SyntaxError: missing : after property id (shell):1

// This works:
> db.test.update({ "domain" : site}, { $inc : {"counts.year.10" : 1,
      "counts.month.5" : 1}}, upsert=true);

I guess the problem is in the way the JS object is created: for instance var t = 10; doc = {t : 0}; works but var t = 10; doc = {"Test."+t : 0}; does not. How can I work around this?

Thank you,

/David

Share Improve this question asked Apr 19, 2012 at 17:29 OG DudeOG Dude 9362 gold badges12 silver badges23 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

you could try for the JS object:

var t = 10;
var doc = {};
doc["Test."+t] = 0;

or

var t = 10, doc = {};
doc["Test."+t] = 0;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742318057a4421235.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信