I have mongo query which does the group operation on the documents.
I have almost got the expected results except that I want to refine the results without empty or null values.
Currently my query looks like this:
db.productMetadata.aggregate([{$group:{"_id":{"color":"$productAttribute.colour","gender":"$productAttribute.gender"},"count" : {$sum : 1}}}]);
And the results looks something like this:
{ "_id" : { "color" : "BLUE", "gender" : "MEN" }, "count" : 1 } { "_id" : { }, "count" : 4 } { "_id" : { "color" : "NA", "gender" : "WOMEN" }, "count" : 1 } { "_id" : { "color" : "BLACK", "gender" : "MEN" }, "count" : 1 } { "_id" : { "color" : "BROWN", "gender" : "WOMEN" }, "count" : 1 } { "_id" : { "gender" : "MEN" }, "count" : 2 } { "_id" : { "color" : "BEIGE", "gender" : "MEN" }, "count" : 1 } { "_id" : { "color" : "BROWN", "gender" : "MEN" }, "count" : 1 }
I want to remove the rows if any of the group by field values are empty or null in the actual data of DB.
Excepted results should look something like this:
{ "_id" : { "color" : "BLUE", "gender" : "MEN" }, "count" : 1 } { "_id" : { "color" : "NA", "gender" : "WOMEN" }, "count" : 1 } { "_id" : { "color" : "BLACK", "gender" : "MEN" }, "count" : 1 } { "_id" : { "color" : "BROWN", "gender" : "WOMEN" }, "count" : 1 } { "_id" : { "color" : "BEIGE", "gender" : "MEN" }, "count" : 1 } { "_id" : { "color" : "BROWN", "gender" : "MEN" }, "count" : 1 }
Solution 1: In case preservation of all null values[] or null fields in the array itself is not necessary. Filter out the not null elements using $filter , the ( all null elements) array would be empty, filter that out from documents using $match then $sort on values .
MongoDB group by is used to group data from the collection, we can achieve group by clause using aggregate function and group method in MongoDB. While using aggregate function with group by clause query operations is faster as normal query, basically aggregate function is used in multiple condition.
Definition. Evaluates a boolean and returns the opposite boolean value; i.e. when passed an expression that evaluates to true , $not returns false ; when passed an expression that evaluates to false , $not returns true .
MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).
You need an extra $match
pipeline step that will filter the incoming documents based on the embedded field "$productAttribute.colour"
existing and not null:
db.productMetadata.aggregate([ { "$match": { "productAttribute.colour": { "$exists": true, "$ne": null } } }, { "$group": { "_id": { "color": "$productAttribute.colour", "gender": "$productAttribute.gender" }, "count": { "$sum": 1 } } } ]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With