Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group query with multiple $cond?

I want to query like below, but this contains only one $cond.

How to query with two $cond?

collection.aggregate(     {          $match : {              '_id' : {$in:ids}         }      },     {         $group: {             _id: '$someField',             ...             count: {$sum: { $cond: [ { $eq: [ "$otherField", false] } , 1, 0 ] }}         }     },     function(err, result){         ...     } ); 
like image 588
yountae.kang Avatar asked Dec 30 '13 09:12

yountae.kang


People also ask

When to use group by multiple columns in SQL?

Introduction to SQL GROUP BY Multiple Columns 1 Usage of GROUP BY Multiple Columns. When the grouping criteria are defined on more than one column or expressions then all the records that match and have the same values ... 2 Examples. ... 3 Conclusion. ...

How to group values in multiple rows into a single value?

In Power Query, you can group values in various rows into a single value by grouping the rows according to the values in one or more columns. You can choose from two types of grouping operations: Aggregate a column by using an aggregate function.

How to group resultset in SQL with multiple column values?

We can group the resultset in SQL on multiple column values. When we define the grouping criteria on more than one column, all the records having the same value for the columns defined in the group by clause are collectively represented using a single record in the query output.

How do you group values in a Power Query?

In Power Query, you can group values in various rows into a single value by grouping the rows according to the values in one or more columns. You can choose from two types of grouping operations: Aggregate a column by using an aggregate function. Perform a row operation.


1 Answers

You want to use a compound expression inside {$cond:[]} - something like:

collection.aggregate(     {          $match : {              '_id' : {$in:ids}         }      },     {         $group: {             _id: '$someField',             ...             count: {$sum: { $cond: [ {$and : [ { $eq: [ "$otherField", false] },                                                { $eq: [ "$anotherField","value"] }                                      ] },                                      1,                                      0 ] }}         }     },     function(err, result){         ...     } ); 

The $and operator is documented here: http://docs.mongodb.org/manual/reference/operator/aggregation/#boolean-operators

like image 141
Asya Kamsky Avatar answered Nov 02 '22 23:11

Asya Kamsky