Get documents with nested objects matching the counting condition

I am a mongo noob and am working with a mongo collection with entries that look like this:

{
    "cats" [
        {
            "name": "fluffy",
            "color": "red",           
        }, 
        {
            "name": "snowball",
            "color": "white",           
        }, 
    ]
{

I would like to fulfill a request in which all entries containing more than 1 white cat will be recorded. MapReduce looks promising, but seems redundant. Any help is appreciated.

+4
source share
2 answers

To do this, you can use the aggregation structure . You do not need to use the operator $where.

db.collection.aggregate([
    { "$match": { "cats.color": "white" }},
    { "$project": { 
        "nwhite": { "$map": { 
            "input": "$cats", 
            "as": "c",
            "in": { "$cond": [
                { "$eq": [ "$$c.color", "white" ] },
                1, 
                0
            ]}
        }}, 
        "cats": 1
     }},
     { "$unwind": "$nwhite" }, 
     { "$group": { 
         "_id": "$_id", 
         "cats": { "$first": "$cats" }, 
         "nwhite": { "$sum": "$nwhite" }
     }},
    { "$match": { "nwhite": { "$gte" :2 } } } 
])
+4
source

$where. , javascript.

:

db.collection.find({$where: function() {
  return this.cats.filter(function(cat){
    // Filter only white cats
    return cat.color === 'white';
  }).length >= 2;
}});
+2

Source: https://habr.com/ru/post/1606611/


All Articles