Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find by _id on an array of objects in MongoDB database?
To find by _id on an array of objects, use aggregation and avoid using find(). Let us first create a collection with documents −
> db.demo414.insertOne(
... {
... "_id": "110",
... "details":[
... {
... "StudentName":"John",
... "StudentMarks":56
... },
... {
... "StudentName":"Robert",
... "StudentMarks":98
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : "110" }
Display all documents from a collection with the help of find() method −
> db.demo414.find();
This will produce the following output −
{ "_id" : "110", "details" : [ { "StudentName" : "John", "StudentMarks" : 56 }, { "StudentName" : "Robert", "StudentMarks" : 98 } ] }
Following is the query to find by _id on an array of objects −
> db.demo414.aggregate([{$unwind: "$details"}, {$match:{"details.StudentMarks" :56}}] )
This will produce the following output −
{ "_id" : "110", "details" : { "StudentName" : "John", "StudentMarks" : 56 } }Advertisements