Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo db aggregation multiple conditions

I want to project a collection applying exporting a value only if a field is inside a range.

Sort of:

db.workouts.aggregate({
 $match: { user_id: ObjectId(".....") }
},
{
 $project: { 
        '20': { $cond: [ {$gt: [ "$avg_intensity", 20]} , '$total_volume', 0] }
    }    
 })

I need to get the value only if the avg_intensity is inside a certain range. I will then group and sum on the projection result.

What I am trying to do is applying a $gt and $lt filter but with no much success.

db.workouts.aggregate(
{
   $match: { user_id: ObjectId("....") }
},
{
$project: { 
        '20': { $cond: [ [{$gt: [ "$avg_intensity", 20]}, {$lt: [ "$avg_intensity", 25]}] ,    '$total_volume', 0] }
    }    
 })

How may I apply both $gt and $lt conditions?

like image 633
Andrea Campolonghi Avatar asked Apr 23 '14 17:04

Andrea Campolonghi


2 Answers

To combine logical conditions under a $cond operator then wrap the conditions with an $and operator:

db.workouts.aggregate([
    { "$match": { "user_id": ObjectId("....") }},
    { "$project": { 
       "20": { "$cond": [
           { "$and": [ 
               { "$gt": [ "$avg_intensity", 20 ] },
               { "$lt": [ "$avg_intensity", 25 ] }
           ]},    
           "$total_volume", 
           0
       ]}
   }}
])
like image 143
Neil Lunn Avatar answered Sep 17 '22 00:09

Neil Lunn


If I got your requirements right you should put the filter in the match part of the pipeline:

db.workouts.aggregate( [
  { $match: { user_id: ObjectId("...."), "avg_intensity": { $gt: 20, $lte: 25 } } },
  { $group: { _id: ..., count: ... } }
] );
like image 39
Sebastian Avatar answered Sep 17 '22 00:09

Sebastian