Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

MongoDB query to match each element in a documents array to a condition?


1 Answer
Samual Sam

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.