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
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" } ] }Advertisements