Reputation: 304
I want to get the names of people who work in bmw and use these names as filter to find and return the documnents containing the field "car". So the end result must be the last two documents given in this example.
[
{"_id": "235", "name": "indu", "dob": "31/4/15", "company": "bmw"},
{"_id": "236", "name": "prith", "dob": "01/4/98", "company": "bmw"},
{"_id": "237", "name": "rames", "dob": "07/4/00", "company": "renault"},
{"_id": "238", "name": "indu", "salary": "10,000", "car": "yes", "married": "yes"},
{"_id": "239", "name": "prith", "salary": "80,000", "car": "yes", "children": "no"}
]
I appreciate your help, Thanks in advance
Upvotes: 1
Views: 82
Reputation: 22296
You want to use $exists
names = db.collection.distinct{"name", {"company": "bmw"})
db.collection.find({"car": {"$exists": true}, "name": {"$in": names}})
You can also do it in 1 aggregation call although I would not recommend it as It's less efficient.
db.collection.aggregate([
{
"$match": {
"company": "bmw"
}
},
{
$lookup: {
from: "this_collection",
localField: "name",
foreignField: "name",
as: "roots"
}
},
{
"$unwind": "$roots"
},
{
"$replaceRoot": {
"newRoot": "$roots"
}
},
{
"$match": {
"car": {"$exists": true}
}
}
])
Upvotes: 1