mongodb聚合,对象中的分组依据列表

时间:2018-11-14 08:43:22

标签: mongodb group-by aggregate

我正在根据嵌套对象中的给定值执行分组。例如,我的文档结构如下:(对有限的数据表示抱歉)

"_id" : "92623ba7-4ca5-46c7-8d76-c4bc8387ea00",
    "Status" : 2.0,
    "UploadDate" : ISODate("2018-10-30T12:01:19.619Z"),
    "UpdateDate" : ISODate("2018-10-30T12:01:19.619Z"),
    "Request" : "abc123",
    "ShowCaseHtml" : "",
    "PageResult" : [ ],
    "ProductFilter" : {
     "_id" : "9430fb88-2deb-4508-8422-dd67c3a35205",
        "Status" : 2,
        "UploadDate" : ISODate("2018-11-05T10:52:37.122Z"),
        "UpdateDate" : ISODate("2018-11-05T10:52:37.122Z"),
        "ProductPageType" : 0,
        "Categories" : [ ],
        "PriceRanges": [ ],
        "Brands" : [ ],
        "Sellers": [ ],
        "StarRatings" : [ ],
  },
        "BreadCrumbs"[ ]        

查询的结果仅返回对象的一部分,我需要的是完整的对象,但过滤后的版本,这是我的查询

db.getCollection('dbName').aggregate(
    {$match: {"Request": "abc123"}},
    {$project : 
    {"PageResult":1,"ProductFilter":1,"BreadCrumbs":1,"ShowCaseHtml":1}},
    {$unwind: "$PageResult"},
    {$sort:{'PageResult.MarketPlaceProductPrice.ProductPrice':1}},
    {$skip: 2},
    {$limit: 3},
    {$group: {"_id": "$_id", "PageResult": {$push: "$PageResult"}}},
    {$project : 
    {"PageResult.MarketPlaceProductPrice.ProductPrice":1,"_id":0}}
   )

查询结果就像

{
    "PageResult" : [ 
        {
            "MarketPlaceProductPrice" : {
                "ProductPrice" : 1519.00
            }
        }, 
        {
            "MarketPlaceProductPrice" : {
                "ProductPrice" : 2749.00
            }
        }, 
        {
            "MarketPlaceProductPrice" : {
                "ProductPrice" : 3359.00
            }
        }
    ]
}

我也需要ProductFilter,BreadCrumbs和ShowCaseHtml区域,这就是为什么我指定

{$project : 
        {"PageResult":1,"ProductFilter":1,"BreadCrumbs":1,"ShowCaseHtml":1}}

但是我只过滤了PageResult区域,有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用此查询解决了我的问题

   db.getCollection('dbName').aggregate(
    {$match: {"Request":"abc123"}},
    {$project : {"PageResult":1,"ProductFilter":1,"BreadCrumbs":1,"ShowCaseHtml":1}},
    {$unwind: "$PageResult"},
    {$sort:{'PageResult.MarketPlaceProductPrice.ProductPrice':1}},
    {$skip: 2},
    {$limit: 3},
    {$group: {"_id": {"Request":"$Request","ProductFilter":"$ProductFilter","BreadCrumbs":"$BreadCrumbs","ShowCaseHtml":"$ShowCaseHtml"},"PageResult": {$push : "$PageResult"}
  }}
 )