Get documents with nested objects matching count condition

风格不统一 提交于 2019-12-10 17:08:04

问题


I am a mongo noob and am working with a mongo collection with records that look like so:

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

I would like to perform a query that gets all records that have more than 1 white cats. MapReduce looks promising, but seems like overkill. Any help is appreciated.


回答1:


You can use the aggregation framework to do this. You don't need to use the $where operator.

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 } } } 
])



回答2:


Use $where. It is an especially powerful operator as it allows you to execute arbitrary javascript.

For your specific case, try this:

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


来源:https://stackoverflow.com/questions/32484001/get-documents-with-nested-objects-matching-count-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!