MongoDB query where all array items are greater than a specified condition?


You can use $gt operator for this. Let us first create a collection with documents −

> db.arrayElementsNotGreaterThanDemo.insertOne({"Scores":[89,43,32,45]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9e9f9b50a6c6dd317adb3")
}
> db.arrayElementsNotGreaterThanDemo.insertOne({"Scores":[32,33,34,40]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9ea13b50a6c6dd317adb4")
}
> db.arrayElementsNotGreaterThanDemo.insertOne({"Scores":[45,56,66,69]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9ea25b50a6c6dd317adb5")
}
> db.arrayElementsNotGreaterThanDemo.insertOne({"Scores":[46,66,77,88]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9ea3cb50a6c6dd317adb6")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.arrayElementsNotGreaterThanDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd9e9f9b50a6c6dd317adb3"),
   "Scores" : [
      89,
      43,
      32,
      45
   ]
}
{
   "_id" : ObjectId("5cd9ea13b50a6c6dd317adb4"),
   "Scores" : [
      32,
      33,
      34,
      40
   ]
}
{
   "_id" : ObjectId("5cd9ea25b50a6c6dd317adb5"),
   "Scores" : [
      45,
      56,
      66,
      69
   ]
}
{
   "_id" : ObjectId("5cd9ea3cb50a6c6dd317adb6"),
   "Scores" : [
      46,
      66,
      77,
      88
   ]
}

Following is the query where all array items are greater than a specified condition −

> db.arrayElementsNotGreaterThanDemo.find({Scores: {$gt:45}});

This will produce the following output −

{ "_id" : ObjectId("5cd9e9f9b50a6c6dd317adb3"), "Scores" : [ 89, 43, 32, 45 ] }
{ "_id" : ObjectId("5cd9ea25b50a6c6dd317adb5"), "Scores" : [ 45, 56, 66, 69 ] }
{ "_id" : ObjectId("5cd9ea3cb50a6c6dd317adb6"), "Scores" : [ 46, 66, 77, 88 ] }

Updated on: 30-Jul-2019

424 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements