This task can be easily done without the need for dispatching all the callbacks for each user, use the $lookup
pipeline in an aggregate operation where you create a "self-join"
on the users collection, filter the documents using a $match
pipeline to return only those users who share the same course with other users.
For example, the following will return all users who are studying the same course, given there is a field called course
:
User.aggregate([
{ "$match": { "course": { "$exists": true } } },
{
"$lookup": {
"from": "users",
"localField": "course",
"foreignField": "course",
"as": "users_courses"
}
},
{ "$match": { "users_courses.1": { "$exists": true } } }
], callback);
Testing in mongo shell
db.test.insert([
{ "name": "a", "course": "maths" },
{ "name": "b", "course": "english" },
{ "name": "c", "course": "maths" },
{ "name": "d", "course": "science" },
{ "name": "e", "course": "maths" },
{ "name": "f", "course": "history" },
{ "name": "g", "course": "history" }
])
Run aggregate operation
db.test.aggregate([
{ "$match": { "course": { "$exists": true } } },
{
"$lookup": {
"from": "users",
"localField": "course",
"foreignField": "course",
"as": "users_courses"
}
},
{ "$match": { "users_courses.1": { "$exists": true } } }
])
Sample Output
/* 1 */
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ea7"),
"name" : "a",
"course" : "maths",
"users_courses" : [
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ea7"),
"name" : "a",
"course" : "maths"
},
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ea9"),
"name" : "c",
"course" : "maths"
},
{
"_id" : ObjectId("58948c0dd04f1bbdbf331eab"),
"name" : "e",
"course" : "maths"
}
]
}
/* 2 */
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ea9"),
"name" : "c",
"course" : "maths",
"users_courses" : [
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ea7"),
"name" : "a",
"course" : "maths"
},
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ea9"),
"name" : "c",
"course" : "maths"
},
{
"_id" : ObjectId("58948c0dd04f1bbdbf331eab"),
"name" : "e",
"course" : "maths"
}
]
}
/* 3 */
{
"_id" : ObjectId("58948c0dd04f1bbdbf331eab"),
"name" : "e",
"course" : "maths",
"users_courses" : [
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ea7"),
"name" : "a",
"course" : "maths"
},
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ea9"),
"name" : "c",
"course" : "maths"
},
{
"_id" : ObjectId("58948c0dd04f1bbdbf331eab"),
"name" : "e",
"course" : "maths"
}
]
}
/* 4 */
{
"_id" : ObjectId("58948c0dd04f1bbdbf331eac"),
"name" : "f",
"course" : "history",
"users_courses" : [
{
"_id" : ObjectId("58948c0dd04f1bbdbf331eac"),
"name" : "f",
"course" : "history"
},
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ead"),
"name" : "g",
"course" : "history"
}
]
}
/* 5 */
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ead"),
"name" : "g",
"course" : "history",
"users_courses" : [
{
"_id" : ObjectId("58948c0dd04f1bbdbf331eac"),
"name" : "f",
"course" : "history"
},
{
"_id" : ObjectId("58948c0dd04f1bbdbf331ead"),
"name" : "g",
"course" : "history"
}
]
}