4

On MongoDB, how can I select elements with the most recent date from this list :

[{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d55"),
"Date" : "12-09-2018",
"Type" : "A",
"Value" : 73650.14
},
{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d15"),
"Date" : "12-09-2018",
"Type" : "B",
"Value" : 73650.14
},
{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d58"),
"Date" : "13-09-2018",
"Type" : "A",
"Value" : 80000
},
{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d56"),
"Date" : "13-09-2018",
"Type" : "B",
"Value" : 800000
}]

In order to obtain this list :

[{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d58"),
"Date" : "13-09-2018",
"Type" : "A",
"Value" : 80000
},
{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d56"),
"Date" : "13-09-2018",
"Type" : "B",
"Value" : 800000
}]

It is probably easy but I just cannot make it despite many researches. I tried to make it with the $group operator but I have never found how to push the desired values (either I only got the Date or all elements without any filter).

I am new on Mongo DB and I would really appreciate your help.

Thanks

FLOAT01
  • 41
  • 2

1 Answers1

0

The following query for MongoDB 3.6 adds a new date field to each document, groups by that field and pushes documents in that group into an array, sorts by the _id (date) in descending order, limits to the first document (most recent date), unwinds the array of documents, and then cleans up result by replacing the root of each document and projecting the original fields.

db.colx.aggregate([{
  $addFields: {
    ISODate: {
      $dateFromString: {
        dateString: "$Date"
      }
    }
  }
}, {
  $group: {
    _id: "$ISODate", 
    items: {
      $push: "$$ROOT"
    }
  }
}, {
  $sort: {
    _id: -1
  }
}, {
  $limit: 1
}, {
  $unwind: "$items"
}, {
  $replaceRoot: {
    newRoot: "$items"
  }
}, {
  $project: {
    _id: 1, 
    Date: 1, 
    Type: 1, 
    Value: 1
  }
}])

Output:

{ "_id" : ObjectId("5c5064f39d0c4b52cf6d1d58"), "Date" : "13-09-2018", "Type" : "A", "Value" : 80000 }
{ "_id" : ObjectId("5c5064f39d0c4b52cf6d1d56"), "Date" : "13-09-2018", "Type" : "B", "Value" : 800000 }
Jonathan
  • 1,382
  • 1
  • 13
  • 13