A single MongoDB query to orderby date and group by user

MongoDBDatabaseBig Data Analytics

For this, simply use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo243.insertOne({"userId":1,dueDate:new ISODate("2019-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4575f81627c0c63e7dba5f")
}
> db.demo243.insertOne({"userId":2,dueDate:new ISODate("2019-11-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4576011627c0c63e7dba60")
}
> db.demo243.insertOne({"userId":2,dueDate:new ISODate("2020-01-31")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4576151627c0c63e7dba61")
}
> db.demo243.insertOne({"userId":1,dueDate:new ISODate("2010-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e45761b1627c0c63e7dba62")
}

Display all documents from a collection with the help of find() method −

> db.demo243.find();

This will produce the following output −

{ "_id" : ObjectId("5e4575f81627c0c63e7dba5f"), "userId" : 1, "dueDate" : ISODate("2019-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e4576011627c0c63e7dba60"), "userId" : 2, "dueDate" : ISODate("2019-11-10T00:00:00Z") }
{ "_id" : ObjectId("5e4576151627c0c63e7dba61"), "userId" : 2, "dueDate" : ISODate("2020-01-31T00:00:00Z") }
{ "_id" : ObjectId("5e45761b1627c0c63e7dba62"), "userId" : 1, "dueDate" : ISODate("2010-01-10T00:00:00Z") }

Following is the query to orderby date and group by user −

> db.demo243.aggregate({
...   $group: {
...      _id : '$userId',
...      dueDate: { $max: '$dueDate'}
...   }
...})

This will produce the following output −

{ "_id" : 2, "dueDate" : ISODate("2020-01-31T00:00:00Z") }
{ "_id" : 1, "dueDate" : ISODate("2019-01-10T00:00:00Z") }
raja
Published on 30-Mar-2020 17:11:56
Advertisements