【问题标题】:Get documents with nested objects matching count condition获取嵌套对象匹配计数条件的文档
【发布时间】:2016-10-31 06:04:47
【问题描述】:

我是一个 mongo 菜鸟,我正在使用一个 mongo 集合,其中的记录看起来像这样:

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

我想执行一个查询来获取所有拥有超过 1 只白猫的记录。 MapReduce 看起来很有希望,但似乎有点矫枉过正。任何帮助表示赞赏。

【问题讨论】:

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您可以使用aggregation framework 来执行此操作。你don't need 使用$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 } } } 
])

【讨论】:

    【解决方案2】:

    使用$where。它是一个特别强大的运算符,因为它允许您执行任意 javascript。

    对于您的具体情况,试试这个:

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

    【讨论】:

    • 如果我想匹配 cat 数组之外的额外字段,例如:cat type:1 我将如何做到这一点?
    • 此时它只是纯 javascript,因此在 $where 函数中,您只需使用 && this.type === 1 扩展您的布尔返回。这里的关键是 where 函数中的 this 值是您正在迭代的文档。
    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2022-11-05
    • 2019-03-27
    • 2021-05-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    相关资源
    最近更新 更多