简体   繁体   English

用JavaScript查询Mongo

[英]Mongo query in javascript

I am using javascript to run a 2-pronged search. 我正在使用javascript运行2叉搜索。 Variable test has a count of 5. The js part runs however it does not run the mongodb query. 变量test的计数为5。js部分运行,但是不运行mongodb查询。 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. 如下所示,mongo查询给出的计数为15,该变量仅在变量test; test [4] .count = 15中指向对象的对象编号4。 There is no query from 0 to 3. 0到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. 似乎正在跳过查询直到结束。

The issue with your current approach is that you are not explicitly printing the result of the count() in your for loop. 当前方法的问题在于您没有在for循环中显式打印count()的结果。 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. mongo shell打印最后执行的命令的结果,这就是为什么当循环退出时您偶然看到最后一个计数的输出的原因。

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: 您还可以通过将查询谓词作为count()的参数,来更简洁地编写查询,例如:

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

For more information on working with cursors, see Iterate a Cursor in the mongo Shell . 有关使用游标的更多信息,请参阅mongo Shell中迭代游标

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM