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}}}
])
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
This is the query that mongoose prints:
Mongoose: users.aggregate([
{"$match":{"id":{"$in":["0","1","2"]},"p": {$in: 'db.groups.distinct("p", {"enable":true)'}},
{"$group":{"_id":"$v","number":{"$sum":1}}}
])
Can anyone help me how can i pass the inner query from javascript?
UPDATE: The collections are sharded so i cannot user $lookup this is the reason i want to use the $in with distinct
You could execute first the inner query and use the result in the aggregate.
It is also possible to do this directly in the aggregate using
$lookupstage. Here is the doc https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#pipe._S_lookupThe result would look like
You can $lookup which attach a document to each user based on a decided field.
Then you match and group.
Note it is also possible to match with part of the query before to lookup to reduce the number in the lookup phase.