

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 } }
- Related Questions & Answers
- Find all documents that have two specific id's in an array of objects in MongoDB?
- How to group array of objects by Id in JavaScript?
- How to find by id in MongoDB?
- Sorting an array of objects by an array JavaScript
- Creating an array of objects based on another array of objects JavaScript
- Querying on an array of objects for specific nested documents with MongoDB?
- How can I find documents in MongoDB based on the number of matched objects within an array?
- Update an array of strings nested within an array of objects in MongoDB
- Can we search an array of objects in MongoDB?
- Pull multiple objects from an array in MongoDB?
- Sorting an array of objects by property values - JavaScript
- Sort an array of objects by multiple properties in JavaScript
- MongoDB query to find multiple matchings inside array of objects?
- Matching MongoDB collection items by id?
- Filter an array containing objects based on another array containing objects in JavaScript
Advertisements