- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
MongoDB query for Partial Object in an array
Let us first create a collection with documents −
> db.queryForPartialObjectDemo.insertOne({_id:new ObjectId(), "StudentDetails": [{"StudentId":1, "StudentName":"Chris"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5cdfcf55bf3115999ed51206") } > db.queryForPartialObjectDemo.insertOne({_id:new ObjectId(), "StudentDetails": [{"StudentId":2, "StudentName":"David"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5cdfcf55bf3115999ed51207") }
Following is the query to display all documents from a collection with the help of find() method −
> db.queryForPartialObjectDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cdfcf55bf3115999ed51206"), "StudentDetails" : [ { "StudentId" : 1, "StudentName" : "Chris" } ] } { "_id" : ObjectId("5cdfcf55bf3115999ed51207"), "StudentDetails" : [ { "StudentId" : 2, "StudentName" : "David" } ] }
First Approach
Following is the query for partial object in array with MongoDB −
> db.queryForPartialObjectDemo.find({StudentDetails: {StudentId: 1, "StudentName" : "Chris"}});
This will produce the following output −
{ "_id" : ObjectId("5cdfcf55bf3115999ed51206"), "StudentDetails" : [ { "StudentId" : 1, "StudentName" : "Chris" } ] }
Second Approach
Following is the query for partial object in an array with dot notation −
> db.queryForPartialObjectDemo.find({"StudentDetails.StudentName":"Chris"});
This will produce the following output −
{ "_id" : ObjectId("5cdfcf55bf3115999ed51206"), "StudentDetails" : [ { "StudentId" : 1, "StudentName" : "Chris" } ] }
- Related Articles
- MongoDB query to access an object in an array
- MongoDB query to remove empty objects in an object-array?
- MongoDB query for capped sub-collection in an array
- MongoDB query to find data from an array inside an object?
- Query on the last object of an array with MongoDB
- MongoDB query for array concatenation?
- Search for partial value match in an Array in PHP
- MongoDB query to update array object in index N?
- MongoDB syntax for updating an object inside an array within a document?
- MongoDB query to replace value in an array?
- Is it possible to use MongoDB to query for entries that have a particular value in a field in an object in an array?
- MongoDB query to change simple field into an object?
- MongoDB query in object of arrays
- MongoDB query to push document into an array
- MongoDB query to update an array using FindAndUpdate()?

Advertisements