To query on the last object of an array, use aggregate(). Let us create a collection with documents −
> db.demo103.insertOne( { "Details" : [ { "StudentId" : 101, "Details" : "MongoDB" }, {"StudentId" : 102, "Details" : "MySQL" }, { "StudentId" : 103, "Details" : "Java" } ], "Details1" : [ { "StudentId" : 104, "Number" : 3 } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5e2ed2dd9fd5fd66da21446e") }
Display all documents from a collection with the help of find() method −
> db.demo103.find();
This will produce the following output −
{ "_id" : ObjectId("5e2ed2dd9fd5fd66da21446e"), "Details" : [ { "StudentId" : 101, "Details" : "MongoDB" }, { "StudentId" : 102, "Details" : "MySQL" }, { "StudentId" : 103, "Details" : "Java" } ], "Details1" : [ { "StudentId" : 104, "Number" : 3 } ] }
Here is how you can query to on the last object of an array −
> db.demo103.aggregate([ { $project: { Details1: 1, Details: {$arrayElemAt: ["$Details", -1]} } }, { $match: {"Details.StudentId": 103} } ])
This will produce the following output −
{ "_id" : ObjectId("5e2ed2dd9fd5fd66da21446e"), "Details1" : [ { "StudentId" : 104, "Number" : 3 } ], "Details" : { "StudentId" : 103, "Details" : "Java" } }