如何在mongodb中查询以获取具有计数的不同记录

时间:2017-02-21 08:06:19

标签: mongodb

我的收藏名称是transactions。 我正在分享交易集合的对象

{
    "_id" : ObjectId("58aaec83f1dc6914082afe31"),
    "amount" : "33.00",
    "coordinates" : {
        "lat" : "4.8168",
        "lon" : "36.4909"
    },
    "cuisine" : "Mexican",
    "date" : ISODate("0062-02-22T11:46:52.738+05:30"),
    "location" : {
        "address" : "2414 Trudie Rue",
        "city" : "West Alisa",
        "state" : "New York",
        "zip" : "10000"
    },
    "place_name" : "Outdoors",
    "place_type" : "Wooden"
},
{
    "_id" : ObjectId("58aaec83f1dc6914082afe32"),
    "amount" : "557.00",
    "coordinates" : {
        "lat" : "-36.6784",
        "lon" : "131.3698"
    },
    "cuisine" : "Australian",
    "date" : ISODate("1294-10-04T19:53:15.562+05:30"),
    "location" : {
        "address" : "5084 Buckridge Cove",
        "city" : "Sylviaview",
        "state" : "Hawaii",
        "zip" : "51416-6918"
    },
    "place_name" : "Toys",
    "place_type" : "Cotton"
},
{
    "_id" : ObjectId("58aaec83f1dc6914082afe33"),
    "amount" : "339.00",
    "coordinates" : {
        "lat" : "45.1468",
        "lon" : "91.4097"
    },
    "cuisine" : "Mexican",
    "date" : ISODate("1568-11-25T02:54:53.046+05:30"),
    "location" : {
        "address" : "94614 Harry Island",
        "city" : "Cartwrightside",
        "state" : "Louisiana",
        "zip" : "18825"
    },
    "place_name" : "Clothing",
    "place_type" : "Frozen"
},
{
    "_id" : ObjectId("58aaec83f1dc6914082afe34"),
    "amount" : "173.00",
    "coordinates" : {
        "lat" : "-57.2738",
        "lon" : "19.6381"
    },
    "cuisine" : "Australian",
    "date" : ISODate("0804-05-07T03:00:07.724+05:30"),
    "location" : {
        "address" : "1933 Lewis Street",
        "city" : "Aufderharville",
        "state" : "Louisiana",
        "zip" : "23416"
    },
    "place_name" : "Beauty",
    "place_type" : "Fresh"
},
{
    "_id" : ObjectId("58aaec83f1dc6914082afe34"),
    "amount" : "173.00",
    "coordinates" : {
        "lat" : "-57.2738",
        "lon" : "19.6381"
    },
    "cuisine" : "Australian",
    "date" : ISODate("0804-05-07T03:00:07.724+05:30"),
    "location" : {
        "address" : "1933 Lewis Street",
        "city" : "Aufderharville",
        "state" : "Louisiana",
        "zip" : "23416"
    },
    "place_name" : "Beauty",
    "place_type" : "Fresh"
}

我希望总数

获取不同美食的列表

输出

{
   "name" : 'Mexican',
   "count" : '2'
},
{
   "name" : 'Australian',
   "count" : '3'
},

我本可以轻松完成 mysql 但我知道mongodb因为我是mongodb的新手

我试过这个例子但我什么都没找到:

db.transactions.aggregate(
    {$group: {_id:'$cuisine'},count:{$sum:1}}
    ).result;

1 个答案:

答案 0 :(得分:1)

请尝试以下代码。你应该按照烹饪记录进行分组并获得它们的数量。稍后在项目管道中,您可以定义最终外观。

db.transactions.aggregate([
{ $group: { _id: "$cuisine", count: { $sum: 1 } } }, 
{ $project:{ _id: 0, name: "$_id", count:"$count" } }
]);