Reputation: 35
I am trying to get the latest (most recent) value (0.224469) in this collection :
{ "_id" : ObjectId("60112357e06d453f0545f0b4"), "glass" : "7835", "ts" : ISODate("2021-01-27T08:24:55.696Z"), "val" : { "litr" : 0.21405 } }
{ "_id" : ObjectId("60112361e06d453f0545f0b5"), "glass" : "7835", "ts" : ISODate("2021-01-27T08:25:05.694Z"), "val" : { "litr" : 0.215108 } }
{ "_id" : ObjectId("60112393e06d453f0545f0ba"), "glass" : "7835", "ts" : ISODate("2021-01-27T08:25:55.698Z"), "val" : { "litr" : 0.224469 } }
I used MAX of "ts" (timestamp of data insertion) field to get the value of field "litr". I tried the following:
db.glasss_data.aggregate([
{"$match": {"glass": "7835"}},
{"$group": {"_id": null,"MAX(ts)": {"$max": "val"}}}
])
the returned result:
{ "_id" : null, "MAX(ts)" : "val" }
I expect to get: 0.224469 in the result
Thank you very much.
Upvotes: 1
Views: 56
Reputation: 22956
You need to tell mongo that you are referring one of the fields in the document.
To say that $
should be prefixed.
"$max": "val"}
should be
"$max": "$val"}
To get the latest data, you can do sort then limit 1
db.collection.aggregate([
{
"$match": {
"glass": "7835"
}
},
{
$sort: {
"ts": -1
}
},
{
$limit: 1
}
])
Upvotes: 1