如何在MongoDB中使用$ unwind和$ match?

时间:2019-01-03 21:32:51

标签: mongodb

我有以下格式的文件:

// Run a text search against the index
$qb = $dm->createQueryBuilder('Product')
    ->text('words you are looking for');

以下查询正确返回平均值。

{
  "P": {
        "Workspaces": [
           {
              "Key": "Value1",
              "Size": 2.27,
              "Status": 'something'
           },
            {
              "Key": "Value2",
              "Size": 3.27,
              "Status": 'somethingelse'
           }
         ]
     }
}

我试图添加一个匹配项以过滤状态,如下所示。但是,即使有状态匹配的文档,我也没有得到任何结果。我正在尝试在取平均值之前过滤结果。我在这里想念东西吗?

db.collection.aggregate([ 
          { $unwind: "$P.Workspaces" }, 
          { $group: { _id: "$P.Workspaces.Key", average: { $avg: "$P.Workspaces.Size" } } } 
      ])

1 个答案:

答案 0 :(得分:0)

db.articles.aggregate(
[ { $match : { author : "dave" } } ]
);

这些示例使用一个名为articles的集合以及以下文档:

{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 } { "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 } { "_id" : ObjectId("55f5a192d4bede9ac365b257"), "author" : "ahn", "score" : 60, "views" : 1000 } { "_id" : ObjectId("55f5a192d4bede9ac365b258"), "author" : "li", "score" : 55, "views" : 5000 } { "_id" : ObjectId("55f5a1d3d4bede9ac365b259"), "author" : "annT", "score" : 60, "views" : 50 }