在多次出现的mongodb集合中查找值

时间:2017-08-22 23:53:07

标签: mongodb mongodb-query mongojs

我有一个包含以下文件的集合:

{id: 1, "year": "12", "type": "checking", "location": "nyc", "category" : "Admin"}
{id: 2, "year": "15", "type": "checking", "location": "ma", "category": "Normal"}
{id: 3, "year": "12", "type": "credit", "location": "nyc","category": "Admin"}
{id: 4, "year": 12, "type": "checking", "location": "nyc", "category" : "Admin"}

现在,我想计算多次出现符合标准位置的'类型':nyc,年份:12,类别:管理员 所以期望的结果是 {"Checking": 2}

我可以通过什么方式实现上述目标?

1 个答案:

答案 0 :(得分:0)

使用$ match和$ group

db.collectionname.aggregate({$match: {location: 'nyc', year:'12', category:'Admin'}},
{$group: {_id:'$type', count:{$sum:1}}},
{$match:{count: {$gt:1}}}
)