Reputation: 1364
I am trying to sort my response based on the highest occurrence of a postID and within a date.
My collection structure:
[
{
"postID": "2",
"date": "2017-04-11 21:40:52",
},
{
"postID": "1",
"date": "2017-04-11 21:40:52",
},
{
"postID": "2",
"date": "2017-04-11 21:40:52",
},
{
"postID": "2",
"date": "2017-04-11 21:40:52",
},
]
So in this case, the highest occurrence is the postID: 2. So I want something like:
{
postID: 2,
postID: 1
}
Note: Remember that I need to search in between two dates as well.
Sorry if this is too obvious. I don't even know how to begin making the Mongo's/mongoose' find search.
My Stack:
Any input will help. Thanks
Upvotes: 1
Views: 720
Reputation: 191799
You can use the MongoDB aggregation framework to group on a specific property. Mongoose has a low-level wrapper around the aggregation framework.
You can $group
with the postID
as the _id which will give you the unique values for each. Then you can $sort
. You can also use $project
to rename the property back to postID
if you prefer:
Collection.aggregate([
{$group: {_id: "$postID"}},
{$sort: {_id: -1}},
{$project: {postID: "$_id", _id: 0}}
]);
Upvotes: 1