How to query a document in MongoDB comparing fields from an array?

MongoDBDatabaseBig Data Analytics

To compare fields from an array, use $gt and $lt. Let us create a collection with documents −

> db.demo147.insertOne({"Details":[{"Score":45},{"Score":46}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32fa21fdf09dd6d08539be")
}
> db.demo147.insertOne({"Details":[{"Score":65},{"Score":86}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32fa40fdf09dd6d08539bf")
}

Display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e32fa21fdf09dd6d08539be"),
   "Details" : [
      {
         "Score" : 45
      },
      {
         "Score" : 46
      }
   ]
}
{
   "_id" : ObjectId("5e32fa40fdf09dd6d08539bf"),
   "Details" : [
      {
         "Score" : 65
      },
      {
         "Score" : 86
      }
   ]
}

Here is how to query a document in MongoDB comparing fields from an array −

> db.demo147.find({ 'Details.Score': { $gt: 45, $lt: 50 }});

This will produce the following output −

{ "_id" : ObjectId("5e32fa21fdf09dd6d08539be"), "Details" : [ { "Score" : 45 }, { "Score" : 46 } ] }
raja
Published on 31-Mar-2020 12:48:36
Advertisements