- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Query on the last object of an array with MongoDB
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" } }
Advertisements