Reputation: 494
I have this sample 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"
}
I want to fetch the documents which have distinct parrent_id
and have oldest create_date
How I can Do this?
Upvotes: 0
Views: 250
Reputation: 48356
Please try this one. Firstly, sort the create_date
in ascending order, and group by parrent_id
and pick the oldest record for each parrent_id
to meet distinct requirement.
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'}
}
}]);
Upvotes: 1