0

I'm getting a strange result when trying to use eval with the args argument. The following works fine:

> db.eval(function(coll) {
  var res = db[coll].find({});
  return(res.count());
}, ['KenColl'])
1438

But when I pass a second argument, I always get empty results, even if I don't use it:

> db.eval(function(coll, query) {
  var res = db[coll].find({});
  return(res.count());
}, ['KenColl', {}])
0

Am I misunderstanding something about eval and args? I'm running version 2.4.3 of both mongod and the MongoDB shell.

0

1 Answer 1

1

For db.eval you shouldn't pass the arguments as an array, just pass them into the function.

The following example should work:

db.eval(function(coll, query) {
  var res = db[coll].find(query);
  return(res.count());
}, 'KenColl', {})

p.s. your first example only works because in javascript db['KenColl'] === db[['KenColl']]

Sign up to request clarification or add additional context in comments.

5 Comments

Did this change in recent versions of the DB? I'm looking at the "Definitive Guide" book by Chodorow and Dirolf, and on page 105 it shows db.eval taking an array as the second argument. Or is that just an error in the text?
if you pass it an array and the function expects a single argument then the argument will be an array with however many arguments you put in it.
@AsyaKamsky: in the book though, it shows db.eval("function(x,y,z){ return x+y+z; }", [num1, num2, num3]), which I just confirmed in my shell doesn't work as expected.
yeah, I just checked - that syntax doesn't work with spidermonkey shell with 2.0 nor with V8 shell in 2.4. That book was written circa v1.4(?) unless you have a new printing...
I just confirmed, this example is NOT in the new printing of the book so you are looking at the older one. New one: amazon.com/MongoDB-Definitive-Guide-Kristina-Chodorow/dp/…

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.