一个集合中有很多项目,每个项目都有很多记录,有些有新日期的记录,有些有周或/和月的旧记录。我需要一个查询,它返回每个项目的最新记录。在 .aggregate() 的情况下,我需要提交完整的“数据”。我想要使用 mongodb $group 这个结果,每个设备的记录应该是最新的。
{
"result" : [
{
"_id" : 29,
"gateway_id" : 1,
"data" : [
{
"r" : 203,
"v" : 3002
},
{
"r" : 221,
"v" : 3006
}
],
"device_id" : 29,
"date_time" : "a"
},
{
"_id" : 28,
"gateway_id" : 1,
"data" : [
{
"r" : 203,
"v" : 3002
},
{
"r" : 221,
"v" : 3006
}
],
"device_id" : 28,
"date_time" : "b"
},
{
"_id" : 27,
"gateway_id" : 1,
"data" : [
{
"r" : 203,
"v" : 3642
},
{
"r" : 221,
"v" : 3666
}
],
"device_id" : 27,
"date_time" : "a"
}
],
"ok" : 1
}
Run Code Online (Sandbox Code Playgroud)
我想要使用 mongodb $group 这个结果,每个设备的记录应该是最新的。
Cor*_*son 10
我的答案是半相关的,但我加入了convo,因为我在寻找这个时降落在这里。我想对字段上唯一的列表进行分组,email
并返回在组中找到的第一个文档,类似于 SQL 不同查询。
client
.collection('email_list')
.aggregate([
// group documents unique by "email" field, add a new prop "doc" with the full document of the first doc found in the DB
{ $group: { _id: '$email', doc: { $first: '$$ROOT' } } },
// replace the "root" document with the first document found in the DB
{ $replaceRoot: { newRoot: '$doc' } },
])
.toArray()
Run Code Online (Sandbox Code Playgroud)
尝试使用以下代码段
db.collection.aggregate([
{$group: {
"_id": "$device_id",
"gateway_id": {"$last":"$gateway_id"},
"data": {"$last": '$data'},
"date": {"$last": '$date_time'},
}},
{$project: {
"device_id": "$_id",
"gateway_id": "$gateway_id",
"data": "$data",
"date_time": "$date"
}},
{$sort: {
"date": -1
}}
]);
Run Code Online (Sandbox Code Playgroud)
在上面按设备 id 和日期查询组中,数据和 gateway_id 将在每一行中是最新的。