How to query MongoDB a value with $lte and $in?


Let us first create a collection with documents −

> db.queryMongoValueDemo.insertOne(
   {
      _id:101,
      "ScoreDetails":[{Score:80},{Score:45},{Score:25},{Score:70}]
   }
);
{ "acknowledged" : true, "insertedId" : 101 }
> db.queryMongoValueDemo.insertOne(
   {
      _id:102,
      "ScoreDetails":[{Score:80},{Score:24},{Score:34}]
   }
);
{ "acknowledged" : true, "insertedId" : 102 }
> db.queryMongoValueDemo.insertOne(
   {
      _id:103,
      "ScoreDetails":[{Score:99},{Score:95}]
   }  
);
{ "acknowledged" : true, "insertedId" : 103 }

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

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

This will produce the following output −

{
   "_id" : 101,
   "ScoreDetails" : [
      {
         "Score" : 80
      },
      {
         "Score" : 45
      },
      {
         "Score" : 25
      },
      {
         "Score" : 70
      }
   ]
}
{
   "_id" : 102,
   "ScoreDetails" : [
      {
         "Score" : 80
      },
      {
         "Score" : 24
      },
      {
         "Score" : 34
      }
   ]
}
{
   "_id" : 103,
   "ScoreDetails" : [
      {
         "Score" : 99
      },
      {
         "Score" : 95
      }
   ]
}

Query for $lte and $in operator implemented by $not along with $gt operator −

> db.queryMongoValueDemo.find({
   "ScoreDetails.Score": {
      "$eq": 80,
      "$not": { "$gt": 80 }
   }
});

This will produce the following output −

{ "_id" : 101, "ScoreDetails" : [ { "Score" : 80 }, { "Score" : 45 }, { "Score" : 25 }, { "Score" : 70 } ] }
{ "_id" : 102, "ScoreDetails" : [ { "Score" : 80 }, { "Score" : 24 }, { "Score" : 34 } ] }
raja
Published on 14-Jun-2019 17:24:12
Advertisements