
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 to Match Each Element in a Document's Array to a Condition
You can use every() in MongoDB for this. Let us create a collection with documents −
> db.arrayConditionDemo.insertOne({"Name":"John","Marks":[40,43,45]}); { "acknowledged" : true, "insertedId" : ObjectId("5cbdbd06de8cc557214c0e1a") } > db.arrayConditionDemo.insertOne({"Name":"Mike","Marks":[45]}); { "acknowledged" : true, "insertedId" : ObjectId("5cbdbd17de8cc557214c0e1b") } > db.arrayConditionDemo.insertOne({"Name":"Chris","Marks":[43,45,59,69,78,89]}); { "acknowledged" : true, "insertedId" : ObjectId("5cbdbd3cde8cc557214c0e1c") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.arrayConditionDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cbdbd06de8cc557214c0e1a"), "Name" : "John", "Marks" : [ 40, 43, 45 ] } { "_id" : ObjectId("5cbdbd17de8cc557214c0e1b"), "Name" : "Mike", "Marks" : [ 45 ] } { "_id" : ObjectId("5cbdbd3cde8cc557214c0e1c"), "Name" : "Chris", "Marks" : [ 43, 45, 59, 69, 78, 89 ] }
Following is the query to match each element in a documents array to a condition −
> db.arrayConditionDemo.find("return this.Marks.every(function(m) { return (m >= 40 && m<= 100) })");
This will produce the following output −
{ "_id" : ObjectId("5cbdbd06de8cc557214c0e1a"), "Name" : "John", "Marks" : [ 40, 43, 45 ] } { "_id" : ObjectId("5cbdbd17de8cc557214c0e1b"), "Name" : "Mike", "Marks" : [ 45 ] } { "_id" : ObjectId("5cbdbd3cde8cc557214c0e1c"), "Name" : "Chris", "Marks" : [ 43, 45, 59, 69, 78, 89 ] }
Advertisements