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
Is it possible to use MongoDB to query for entries that have a particular value in a field in an object in an array?
Yes, to query for a field in an object in the array with MongoDB, use the following syntax −
db.yourCollectionName.find({"yourOuterFieldName": { $elemMatch: { "yourInnerFieldName": "yourValue" } } } ).pretty();
To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.objectInAnArrayDemo.insertOne({ "StudentDetails": [{
"StudentName": "John", "StudentMessage": "Hi"}, {"StudentName": "Larry", "StudentMessage": "Hello"}]})
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92635d36de59bd9de06381")
}
> db.objectInAnArrayDemo.insertOne({ "StudentDetails": [{
"StudentName": "Carol", "StudentMessage": "Hello"}, {"StudentName": "David", "StudentMessage": "Good Morning"}]})
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92637936de59bd9de06382")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.objectInAnArrayDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c92635d36de59bd9de06381"),
"StudentDetails" : [
{
"StudentName" : "John",
"StudentMessage" : "Hi"
},
{
"StudentName" : "Larry",
"StudentMessage" : "Hello"
}
]
}
{
"_id" : ObjectId("5c92637936de59bd9de06382"),
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentMessage" : "Hello"
},
{
"StudentName" : "David",
"StudentMessage" : "Good Morning"
}
]
}
Here is the query for a field in an object in the array with MongoDB −
> db.objectInAnArrayDemo.find({"StudentDetails": { $elemMatch: { "StudentMessage": "Good Morning" } } } ).pretty();
The following is the output −
{
"_id" : ObjectId("5c92637936de59bd9de06382"),
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentMessage" : "Hello"
},
{
"StudentName" : "David",
"StudentMessage" : "Good Morning"
}
]
}Advertisements