MongoDB - distinct and count, the simplest case

时间:2015-06-03 21:40:06

标签: mongodb count distinct mlab

I have database XXX and collection YYY in MongoDB (using MongoLab).

Here is a sample record:

{
 "_id": {
    "$oid": "551a5asdfsdfsdfs"
 },
 "_class": "com.test.com",
 "mvid": "d0fffsdfs"

}

I would like to retrieve all distinct values of the field "mvid" and count them. Here is what found on the internet:

db.YYY.aggregate([{ $group: { _id: "$mvid"}  },{ $group: { _id: 1, count: { $sum: 1 } } }])

I also tried

XXX.YYY.aggregate([{ $group: { _id: "$mvid"}  },{ $group: { _id: 1, count: { $sum: 1 } } }])

I put the above into command text box, in both cases I get the following error message: "We encountered an error while parsing your JSON. Please check your syntax (e.g. ensure you are using double quotes around both your field names and values) and try again."

What am I doing wrong?

2 个答案:

答案 0 :(得分:2)

用于查找每个mvid的计数:

db.YYY.aggregate([{$group: {_id: "$mvid", count: {$sum: 1}}}])

用于查找不同mvids的计数:

db.YYY.aggregate([{$group: {_id: "$mvid", count: {$sum: 1}}}, {$group: {_id: null, count: {$sum: 1}}}, {$project: {_id: 0, count: 1}}])

答案 1 :(得分:2)

该命令文本框用于为下拉列表中选择的任何命令提供JSON格式的参数。 aggregate不是列出的命令之一,因此您似乎需要在本地安装MongoDB shell,然后远程连接到MongoLab数据库并运行命令。

有关安装MongoDB shell并连接到MongoLab的详细信息,请参阅this blog post