Syntax error How to find latest entries in array over all MongoDB documents?

How to find latest entries in array over all MongoDB documents?



To find latest entries in array over all document, use aggregate(). Let us create a collection with documents −

> db.demo179.insertOne(
...{
...   "Name":"Chris",
...   "Details": [
...   {
...      "Id":101,
...      "Subject":"MongoDB"
...   },
...   {
...      "Id":102,
...      "Subject":"MySQL"
...   }
...   ]
...}
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3980299e4f06af551997f9")
}
> db.demo179.insertOne(
...{
...   "Name":"David",
...   "Details": [
...   {
...      "Id":103,
...      "Subject":"Java"
...   },
...   {
...      "Id":104,
...      "Subject":"C"
...   }
...   ]
...}
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e39802a9e4f06af551997fa")
}

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

> db.demo179.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e3980299e4f06af551997f9"),
   "Name" : "Chris",
   "Details" : [
      {
         "Id" : 101,
         "Subject" : "MongoDB"
      },
      {
         "Id" : 102,
         "Subject" : "MySQL"
      }
   ]
}
{
   "_id" : ObjectId("5e39802a9e4f06af551997fa"),
   "Name" : "David",
   "Details" : [
      {
         "Id" : 103,
         "Subject" : "Java"
      },
      {
         "Id" : 104,
         "Subject" : "C"
      }
   ]
}

Following is the query to find latest entries in array over all documents −

> db.demo179.aggregate([
...   { "$unwind": "$Details" },
...   { "$sort": { "Details.Id": -1 }  },
...   { "$limit": 2 },
...   {
...      "$group": {
...         "_id": "$Details.Id",
...         "Name" : { "$first": "$Name" },
...         "Details": { "$push": "$Details" }
...      }
...   },
...   {
...      "$project": {
...         "_id": 0, "Name": 1, "Details": 1
...      }
...   }
...])

This will produce the following output −

{ "Name" : "David", "Details" : [ { "Id" : 103, "Subject" : "Java" } ] }
{ "Name" : "David", "Details" : [ { "Id" : 104, "Subject" : "C" } ] }
Updated on: 2020-03-27T07:49:57+05:30

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements