简体   繁体   中英

Mongodb aggregate query with condition

I have to perform aggregate on mongodb in python and unable to do so.

Below is the structure of mongodb document extracted:

{'Category': 'Male',
 'details' :[{'name':'Sachin','height': 6},
             {'name':'Rohit','height': 5.6},
             {'name':'Virat','height': 5}
            ]
}

I want to return the height where name is Sachin by the aggregate function. Basically my idea is to extract data by $match apply condition and aggregate at the same time with aggregate function. This can be easily done by doing in 3 steps with if statements but i'm looking to do in 1 aggregate function.

Please note: there is not fixed length of 'details' value.

Let me know if any more explanation is needed.

You can do a $filter to achieve

db.collection.aggregate([
  {
    $project: {
      details: {
        $filter: {
          input: "$details",
          cond: {
            $eq: [
              "$$this.name",
              "Sachin"
            ]
          }
        }
      }
    }
  }
])

Working Mongo playground

If you use in find , but you need to be aware of positional operator

db.collection.find({
  "details.name": "Sachin"
},
{
  "details.$": 1
})

Working Mongo playground

If you need to make it as object, you can simply use $arrayElemAr with $ifNull

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM