I have a Mongoose schema which is like this:
const mySchema = new mongoose.Schema(
{
_id: String,
coin: String,
closeTime: Number,
volume: Number,
}
I have a bunch of different coins. Is it possible to get the latest document for each unique coin I have based on the closeTime?
Help would be much appreciated! Thanks.
CodePudding user response:
You can use aggregation to sort by latest/newest closeTime
, group by coin
then getting the first document of that group:
mySchema.aggregate([
{ $sort: { closeTime: -1 } },
{ $group: { _id: "$coin", latest: { $first: "$$ROOT" } } }
])
This is sorting with numeric closeTime
in descending order, getting the first/latest document and putting its data into a property called latest
. This should create results like:
[{
"_id" : "2",
"latest" : {
"_id" : ObjectId("6149f106742bb30e2529c453"),
"coin" : "foo",
"closeTime" : 5,
"volume" : 1
}
}
{
"_id" : "1",
"latest" : {
"_id" : ObjectId("6149f111742bb30e2529c45f"),
"coin" : "bar",
"closeTime" : 4,
"volume" : 1
}
}]
You can take this one step further with other aggregation stages to extract/project the underlying coin document.