2016-03-08 50 views
0

我有這個樣本JSON:在mongoDB中查找具有不同和排序的文檔?

{ 
    "_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

我怎樣才能做到這一點?

+0

現在還不清楚你在這裏問什麼。你是什​​麼意思*有不同的'parrent_id'和最早的'create_date' *?你應該考慮編輯你的問題來添加預期的結果。 – styvane

回答

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'} 
            } 
         }]); 
+0

這是給予聚合不是一個功能 – YAM

+0

@YAM,對不起,錯誤,它應該'聚合' – zangw

+0

是的,它現在正在運行 – YAM

相關問題