0

I am using javascript to run a 2-pronged search. Variable test has a count of 5. The js part runs however it does not run the mongodb query. As you can see below, the mongo query gives the count 15 which only address' object number 4 in the variable test;test[4].count =15. There is no query from 0 to 3.

var test=db.categories.find({"path":/English\/TEST/OG/},{"path":1})
test.length()==5



for(i=0;i<test.length();i++)
{
print(i);
db.assets.find({"title.categories":test[i].path}).count()
}
0
1
2
3
4
15

Seems to be skipping the query until the end.

  • related/dupe http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – rlemon Mar 22 '17 at 19:26

1 Answers1

0

The issue with your current approach is that you are not explicitly printing the result of the count() in your for loop. The mongo shell prints the result of the last command executed, which is why you happen to see the output of the last count when the loop exits.

Your code should instead look like:

for (i=0; i<test.length(); i++) {
    print(i);
    print(db.assets.find({"title.categories":test[i].path}).count());
}

You can also write your query more concisely by including the query predicate as a parameter to count(), eg:

    print(db.assets.count({"title.categories":test[i].path}));

For more information on working with cursors, see Iterate a Cursor in the mongo Shell.

Stennie
  • 63,885
  • 14
  • 149
  • 175