sunil shrestha
sunil shrestha

Reputation: 47

Double $match in MongoDB aggregation

I have two collections as

Col1

{"_id":ObjectId("5c13fa0178cd81112f1d5ba5"),
"common_id": 123,
"context":"app"   
}

context has different options as "app", "db", "network"

Col2

{"_id":ObjectId("5c13fa0178cd81112f1d5b34"),
"common_id":123,
"name":"android-app"
"status":"Up"
}

status has different options as "Up","Down","Degraded"

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

Answers (2)

Saravana
Saravana

Reputation: 12817

Try this, you've some syntax errors in your query

  1. $lookup from table is not enclosed with double quotes
  2. $match stage missing {},
  3. $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

Chacliff
Chacliff

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

Related Questions