代码之家  ›  专栏  ›  技术社区  ›  kratos

MongoDB:未知运算符:$filter[duplicate]

  •  0
  • kratos  · 技术社区  · 6 年前

    假设我的收藏中有以下文档:

    {  
       "_id":ObjectId("562e7c594c12942f08fe4192"),
       "shapes":[  
          {  
             "shape":"square",
             "color":"blue"
          },
          {  
             "shape":"circle",
             "color":"red"
          }
       ]
    },
    {  
       "_id":ObjectId("562e7c594c12942f08fe4193"),
       "shapes":[  
          {  
             "shape":"square",
             "color":"black"
          },
          {  
             "shape":"circle",
             "color":"green"
          }
       ]
    }
    

    进行查询:

    db.test.find({"shapes.color": "red"}, {"shapes.color": 1})
    

    或者

    db.test.find({shapes: {"$elemMatch": {color: "red"}}}, {"shapes.color": 1})
    

    (文件1) ,但始终包含所有数组项 shapes

    { "shapes": 
      [
        {"shape": "square", "color": "blue"},
        {"shape": "circle", "color": "red"}
      ] 
    }
    

    不过,我想拿到这份文件 (文件1) color=red :

    { "shapes": 
      [
        {"shape": "circle", "color": "red"}
      ] 
    }
    

    我该怎么做?

    0 回复  |  直到 6 年前
        1
  •  0
  •   KARTHIKEYAN.A    5 年前

    MongoDB 2.2的新功能 $elemMatch projection运算符提供了另一种方法来更改返回的文档,使其仅包含 第一 匹配的 shapes 元素:

    db.test.find(
        {"shapes.color": "red"}, 
        {_id: 0, shapes: {$elemMatch: {color: "red"}}});
    

    返回:

    {"shapes" : [{"shape": "circle", "color": "red"}]}
    

    $ projection operator ,其中 $ 在投影对象中,字段名表示查询中字段的第一个匹配数组元素的索引。以下返回与上面相同的结果:

    db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});
    

    MongoDB 3.2更新

    从3.2版本开始,您可以使用新的 $filter 在投影期间过滤数组的聚合运算符,其好处是 全部的

    db.test.aggregate([
        // Get just the docs that contain a shapes element where color is 'red'
        {$match: {'shapes.color': 'red'}},
        {$project: {
            shapes: {$filter: {
                input: '$shapes',
                as: 'shape',
                cond: {$eq: ['$$shape.color', 'red']}
            }},
            _id: 0
        }}
    ])
    

    结果:

    [ 
        {
            "shapes" : [ 
                {
                    "shape" : "circle",
                    "color" : "red"
                }
            ]
        }
    ]