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 MongoDB documents where all objects in array have specific value?
Let us create a collection with documents −
> db.demo74.insertOne(
... {
... StudentName: "Chris",
... StudentDetails: [{
... "Subject": "MongoDB",
... "isRegular": "Active"
... },{
... "Subject": "MongoDB",
... "isRegular": "InActive"
... },{
... "Subject": "MongoDB",
... "isRegular": "InActive"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29c6b671bf0181ecc4226f")
}
> db.demo74.insertOne({
... name: "document2",
... data: [{
... "Subject": "MongoDB",
... "isRegular": "Active"
... },{
... "Subject": "MongoDB",
... "isRegular": "Active"
... },{
... "Subject": "MongoDB",
... "isRegular": "Active"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29c6b771bf0181ecc42270")
}
Display all documents from a collection with the help of find() method −
> db.demo74.find();
This will produce the following output −
{
"_id" : ObjectId("5e29c6b671bf0181ecc4226f"), "StudentName" : "Chris", "StudentDetails" : [
{ "Subject" : "MongoDB", "isRegular" : "Active" },
{ "Subject" : "MongoDB", "isRegular" : "InActive" },
{ "Subject" : "MongoDB", "isRegular" : "InActive" }
]
}
{
"_id" : ObjectId("5e29c6b771bf0181ecc42270"), "name" : "document2", "data" : [
{ "Subject" : "MongoDB", "isRegular" : "Active" },
{ "Subject" : "MongoDB", "isRegular" : "Active" },
{ "Subject" : "MongoDB", "isRegular" : "Active" }
]
}
Following is the query to find documents where all objects in array have specific value −
> db.demo74.find({ " StudentDetails": { "$not": { "$elemMatch": { "isRegular": { $ne: "Active" } } } }, "StudentDetails.isRegular": "Active" }).pretty();
This will produce the following output −
{
"_id" : ObjectId("5e29c6b671bf0181ecc4226f"),
"StudentName" : "Chris",
"StudentDetails" : [
{
"Subject" : "MongoDB",
"isRegular" : "Active"
},
{
"Subject" : "MongoDB",
"isRegular" : "InActive"
},
{
"Subject" : "MongoDB",
"isRegular" : "InActive"
}
]
}Advertisements