计算不同的子文档字段并输出为命名关键字 [英] Count Distinct Sub document field and Output as Named Keys

查看:51
本文介绍了计算不同的子文档字段并输出为命名关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中,如果我有一个如下所示的集合,

{
    "auctionId" : 22,
    "startDt" : "2017-08-28T06:00:00.000Z",
    "endDt" : "2017-09-04T06:00:00.000Z",
    "status" : "Open",
    "pickupDt" : "2017-09-07T06:00:00.000Z",
    "itmLst" : 
    [ 
        {
            "itemId" : 1,
            "location" : "Open",
            "currentBid" : 13.0,
            "highBidder" : 1897,
            "bidCnt" : 4,
            "catgegory" : "ANTIQUES"
             ...

我该如何使用聚合函数查询它以获取AuctionId = 22的不同类别的计数,并按itmLst.category分组,因此它将返回如下所示的结果集:

{
    "ANTIQUES": 56,
    "TOOLS": 89,
    "JEWLRY": 45,
    ...
}

解决方案

我找到了我要找的答案.该查询:

返回:

谢谢尼尔,尽管我指出了正确的方向.

In MongoDB, If I had a collection that looked like the following,

{
    "auctionId" : 22,
    "startDt" : "2017-08-28T06:00:00.000Z",
    "endDt" : "2017-09-04T06:00:00.000Z",
    "status" : "Open",
    "pickupDt" : "2017-09-07T06:00:00.000Z",
    "itmLst" : 
    [ 
        {
            "itemId" : 1,
            "location" : "Open",
            "currentBid" : 13.0,
            "highBidder" : 1897,
            "bidCnt" : 4,
            "catgegory" : "ANTIQUES"
             ...

How could i query it with an aggregate function to retrieve a count of the distinct categories for auctionId = 22, grouping by itmLst.category, so it would return a result set that would look like this:

{
    "ANTIQUES": 56,
    "TOOLS": 89,
    "JEWLRY": 45,
    ...
}

解决方案

I have found the answer i was looking for. This query:

db.auctions.aggregate([
   { "$match": { "auctionId": 22 } },
   { $unwind:'$itmLst' }, 
   { $group:{_id:'$itmLst.catgegory', freq:{$sum:1}} },
   { $sort:{ "_id": 1 } }
]);

returns:

{
    "_id" : "ANTIQUES",
    "freq" : 9.0
}
{
    "_id" : "APPLIANCES",
    "freq" : 1.0
}
{
    "_id" : "ARTS CRAFTS",
    "freq" : 9.0
}
{
    "_id" : "BOOKS MAGAZINES",
    "freq" : 6.0
}

Thank you Neil for pointing me in the right direction though.

这篇关于计算不同的子文档字段并输出为命名关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆