There are many items in a collection, each has many records, some have records of new dates and some have week or/and month older. I need a query which returns latest last record of each item. In the case of .aggregate() I need that complete "data" filed. I want this result using mongodb $group, the record should be latest for each device.
{
"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
}
I want this result using mongodb $group, the record should be latest for each device.
MongoDB find() method is used to select documents from a specified collection. It also set the cursor position to the selected document. The default find() method gets the documents from the start of the collection.
This means $first returns the first order type for the documents between the beginning of the partition and the current document.
$$NOW is an aggregation variable, which means that it can by used only within aggregation pipeline. Due to the documentation, save() method is deprecated. use insertOne() instead. To insert current date you need to provide date value on the client side.
This means $last returns the last order type for the documents between the current document and the end of the partition.
Try with following snippet
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
}}
]);
In above query group by device id and date, data, and gateway_id will be latest in each row.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With