Reputation: 47
I have two collections as
{"_id":ObjectId("5c13fa0178cd81112f1d5ba5"),
"common_id": 123,
"context":"app"
}
{"_id":ObjectId("5c13fa0178cd81112f1d5b34"),
"common_id":123,
"name":"android-app"
"status":"Up"
}
I am interested in getting result like:
{
"name":"android-app",
}
Only if context is app and status is up for item with same common_id.
I have tried as:
col1.aggregate([{"$match": {"context":"app"}},
{"$lookup": {"from":col2,
"localField": "common_id",
"foreignField": "common_id",
"as": "output_info"}},
{"$unwind": {"path": "$output_info"}},
{"$match": "$output_info.status":"Up"},
{
"$project":{
"$output_info.name":1
}}
])
But its getting error..
Upvotes: 0
Views: 4331
Reputation: 12817
Try this, you've some syntax errors in your query
$lookup
from table is not enclosed with double quotes$match
stage missing {}
, $match
and $project
field name should not start with $
query
db.col1.aggregate([
{"$match": {"context":"app"}},
{"$lookup": {
"from":"col2",
"localField": "common_id",
"foreignField": "common_id",
"as": "output_info"
}},
{"$unwind": {"path": "$output_info"}},
{"$match": {"output_info.status":"Up"}},
{"$project":{"output_info.name":1}}
])
Upvotes: 2
Reputation: 71
My initial suggestion when it comes to mongodb would be to combine the two collections into one and not use an aggregate at all. This data sounds extremely related and combinable. Once combined you could do a query
db.col.find({ context: "app", status: "Up" })
If you must have an aggregate I can look more deeply at the query.
Upvotes: 1