如何解决此MongoDB聚合查询?

时间:2019-04-06 03:19:17

标签: mongodb

集合结构如下:

[{  
      "id":"1",
      "firstname":"Wilhelm",
      "surname":"Röntgen",
      "born":"1845-03-27",
      "Country":"Prussia (now Germany)",
      "bornCountryCode":"DE",
      "City":"Lennep (now Remscheid)",
      "gender":"male",
      "prizes":[  
         {  
            "year":"1901",
            "category":"physics",
            "share":"1",
            "motivation":"\"in recognition of the extraordinary services he has rendered by the discovery of the remarkable rays subsequently named after him\"",
            "affiliations":[  
               {  
                  "name":"Munich University",
                  "city":"Munich",
                  "country":"Germany"
               }
            ]
         }
      ]
}]

我是mongodb的新用户。 我想查找美国所有居住至少10个用户的城市。 这是我写的代码,但没有显示结果... 有人可以帮我解决吗?谢谢...

db.database.aggregate([
{$group:{_id:"$City",count:{$sum:1}},
{$match:{$and:[{count:{$gt:10}}, {Country: "US"}]}}]).pretty()

1 个答案:

答案 0 :(得分:0)

第一个小问题是,您在第2行上缺少结尾},应该是:

{$group:{_id:"$City",count:{$sum:1}}},

现在,如果仅运行管道的$group阶段,您将得到如下结果:

{ "_id" : "Lennep (now Remscheid)", "count" : 1 }

您可以看到Country字段丢失。这就是$match阶段不返回结果的原因。

因此,更好的方法是将过滤器Country移到$group阶段之前的起始位置。

db.database.aggregate([
  {$match:{Country: "US"}},
  {$group:{_id:"$City",count:{$sum:1}}},
  {$match:{count:{$gte:10}}}
])

还要注意,当您提到“至少10”时,我将{$gt:10}更改为{$gte:10}