Find value in a MongoDB Array with multiple criteria?

MongoDBDatabaseBig Data Analytics

To find value in the array with multiple criteria, for example, you can use $elemMatch along with $gt and $lt. The syntax is as follows −

db.yourCollectionName.find({yourFieldName:{$elemMatch:{$gt:yourNegativeValue,$lt:yourPo sitiveValue}}}).pretty();

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Larry","StudentMarks":[-150,150]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77daf6fc4e719b197a12f5")
}
> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Mike","StudentMarks":[19]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77db09fc4e719b197a12f6")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c77daf6fc4e719b197a12f5"),
   "StudentName" : "Larry",
   "StudentMarks" : [
      -150,
      150
   ]
}
{
   "_id" : ObjectId("5c77db09fc4e719b197a12f6"),
   "StudentName" : "Mike",
   "StudentMarks" : [
      19
   ]
}

Here is the query to find value in the array with multiple criteria. For example, here we are considering marks greater than -20 and less than 20 −

> db.findValueInArrayWithMultipleCriteriaDemo.find({StudentMarks:{$elemMatch:{$gt:-20,$lt:20}}}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c77db09fc4e719b197a12f6"),
   "StudentName" : "Mike",
   "StudentMarks" : [
      19
   ]
}
raja
Published on 28-Mar-2019 12:06:33
Advertisements