3

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

> var site = "google.com";
> 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

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that worked var site = "google.com"; var y = 2012; var m = 10; var d = 30; doc = {}; incDoc["counts.year."+y] = 1; incDoc["counts.month."+m] = 1; incDoc["counts.days."+d] = 1; db.test.update({ "domain" : site}, { $inc : incDoc}, upsert=true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.