在mongoDB中查找具有distinct和排序的文档?

时间:2016-03-08 07:31:52

标签: mongodb mongodb-query aggregation-framework

我有这个样本json:

{
     "_id" : ObjectId("56de78e0c8f8759239f20cc8"),    
     "vendor_Name" : "bb group trades",     
     "parrent_id" : "56d6c4400a5eac8a78101c8f",
     "channel_name" : "snapdeal",
     "create_date" : ISODate("2016-03-07T18:30:00.000Z"),
     "product_rating" : "3.9" 
}, 

{
    "_id" : ObjectId("56de7b29c8f8759239f20cca"),
    "vendor_Name" : "bb group trades",
    "parrent_id" : "56d6e2594e8ee6111417e67a",
    "channel_name" : "snapdeal",
    "create_date" : ISODate("2016-03-07T18:30:00.000Z"),
    "product_rating" : null 
},

{
    "_id" : ObjectId("56de7b1ac8f8759239f20cc9"),
    "vendor_Name" : "oyedeal",   
    "parrent_id" : "56d6e2594e8ee6111417e67a",
    "channel_name" : "snapdeal",
    "create_date" : ISODate("2016-03-07T18:30:00.000Z"),
    "product_rating" : "5.0" 
}

我想获取具有不同parrent_id且具有最早create_date

的文档

我怎么做?

1 个答案:

答案 0 :(得分:1)

请尝试这个。首先,按升序对create_date进行排序,然后按parrent_id分组,并为每个parrent_id选择最早的记录,以满足不同的要求。

db.collection.aggregate([
                         // sort the create_date in ascending order
                         {$sort: {create_date: 1}},
                         // group by `parrent_id`, and pick the first element for each field which is the oldest create_date.
                         {$group: {_id: '$parrent_id',
                                   'vendor_Name': {$first: '$vendor_Name'},
                                   'channel_name': {$first: '$channel_name'},
                                   'product_rating': {$first: '$product_rating'}
                                   }
                        }]);