Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

Issue with getting most recent value in a mongodb collection

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.

question from:https://stackoverflow.com/questions/65929715/issue-with-getting-most-recent-value-in-a-mongodb-collection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

playground

db.collection.aggregate([
  {
    "$match": {
      "glass": "7835"
    }
  },
  {
    $sort: {
      "ts": -1
    }
  },
  {
    $limit: 1
  }
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...