根据MongoDB中的字段获取最后的记录
我是Mongo的学习者和新手。我正在尝试根据特定字段获取最后的记录。在SQL 中,按DESC限制1
从PowerAndlevel组中选择 *。因此,在基于DeviceID的SQL查询中,我可以获取每个DeviceID的最后一个记录。我想在mongodb中做同样的事情
[{
_id: "ObjectId(6246ab45e95eac6c85726cfc)"
imageName: "IMG_123456.jpg"
eventTime: "2022-04-01T07:35:30.615Z"
deviceId: "48701ED21819"
},
{
_id: "ObjectId(6246ab45e95eac6c85726cfc)"
imageName: "IMG_123456.jpg"
eventTime: "2022-04-01T07:38:10.543Z"
deviceId: "58701ED21819"
},
{
_id: "ObjectId(6246ab45e95eac6c85726cfc)"
imageName: "IMG_123456.jpg"
eventTime: "2022-04-01T08:05:50.865Z"
deviceId: "48701ED21819"
}]
,并且我正在使用此查询 db.imageevent.aggregate([{{“ $ group”:{“ _id”:{“ deviceId”:“ $ decep但:{eventtime:1}},{$ limit:1}])
结果
[{ "_id" : { "deviceId" : "58701ED21819" } },
{ "_id" : { "deviceId" : "48701ED21819" } }]
,并期望这样的结果
[{
_id: "ObjectId(6246ab45e95eac6c85726cfc)"
imageName: "IMG_123456.jpg"
eventTime: "2022-04-01T07:38:10.543Z"
deviceId: "58701ED21819"
},
{
_id: "ObjectId(6246ab45e95eac6c85726cfc)"
imageName: "IMG_123456.jpg"
eventTime: "2022-04-01T08:05:50.865Z"
deviceId: "48701ED21819"
}]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不需要每个结果的
objectID
,只是公共值和最新日期,您可以通过:如下:如playground
$ first
对于组相同的值很方便。$ max
将为您提供最新日期。这将阻止您对整个集合进行排序,并在查询期间创建大型文档,因为文档的上限大小。
If you don't need the
ObjectId
of each result, just the common values and the latest date, you can simplify it by:As you can see on the playground
The
$first
is convenient for values that are the same for the group. The$max
will give you the latest date.This will prevent you from sorting the entire collection and from creating large documents during the query, since there is a cap size for a document.
$ sort
- 通过EventTime
desc进行排序。$ group
- 组成的deviceId
组,然后将第一个文档通过data
通过$ first
字段。$替换
- 用data
替换输入文档。示例mongo playground
$sort
- Sort byeventTime
DESC.$group
- Group bydeviceId
and take first document intodata
field via$first
.$replaceRoot
- Replace the input document withdata
.Sample Mongo Playground