如何通过JavaScript在MongoDB中传递内部查询 [英] How to pass inner query in mongodb from javascript
问题描述
我想创建一个聚合管道,其中一个匹配项使用其他集合(内部查询)的结果.这是一个例子:
I want to create an aggregation pipeline which one of the matches use results from other collection (inner query). This is an example:
db.users.aggregate([
{"$match":{"id":{"$in":["0","1","2"]},"p": {$in: db.groups.distinct("p", {"enable":true)}}},
{"$group":{"_id":"$v","number":{"$sum":1}}}
])
,我需要通过 javascript 进行查询.实际上,该应用程序是 nodejs 和猫鼬.
and i need to do the query from javascript. Actually the application is nodejs with mongoose.
不幸的是,当猫鼬执行查询时,我得到了:
Unfortunately when mongoose executes the query i get:
MongoError: $in needs an array
这是猫鼬打印的查询:
Mongoose: users.aggregate([
{"$match":{"id":{"$in":["0","1","2"]},"p": {$in: 'db.groups.distinct("p", {"enable":true)'}},
{"$group":{"_id":"$v","number":{"$sum":1}}}
])
有人可以帮助我如何通过javascript传递内部查询吗?
Can anyone help me how can i pass the inner query from javascript?
更新: 集合是 sharded ,所以我不能使用 $ lookup ,这就是我想将$ in与不同字符一起使用的原因
UPDATE: The collections are sharded so i cannot user $lookup this is the reason i want to use the $in with distinct
推荐答案
TLDR;
与猫鼬等效的方法是先运行嵌套查询,然后将结果传递给聚合.
The mongoose equivalent would be to run the nested query first, and pass the results to the aggregation.
groups.distinct("p", {"enable": true}).exec().then(matchingGroups => {
return users.aggregate([
{$match: {"id": {$in: ["0", "1", "2"]}, p: {$in: matchingGroups}}},
{$group:{_id:"$v", number:{$sum:1 }}}
]).exec();
}).then(aggregationResult => {
console.log(aggregationResult);
});
说明
在mongo shell中执行以下脚本时,发生的事情是先提交内部查询(区别),然后将结果传递到外部查询(聚合),然后将其提交执行.这可以通过捕获数据包跟踪来确认.在所附的图像中,我们可以看到首次提交查询(数据包9)的响应(第10和11个数据包),以及聚合查询提交(第12和13个数据包) ).
Explanation
When executing the following script in mongo shell, what happens is that the inner query (distinct) is submitted first, and then the result is passed to the outer query (aggregation) which is then submitted for execution. This can be confirmed by capturing a packet trace. In the attached images, we can see the first query submission (packet 9) the response received (packets 10 and 11), and the aggregation query submission (packets 12 and 13).
这篇关于如何通过JavaScript在MongoDB中传递内部查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!