MongoDB query to match each element in a documents 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 ] }

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements