Tutorialspoint

1 Answer
Nishtha Thakur

The $gt is for greater than, wherein select those documents where the value of the field is greater than the specified value. Let us first create a collection with documents −

> db.performQueryDemo.insertOne({"PlayerDetails":{"PlayerScore":1000,"PlayerLevel":2},"PlayerName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7eba41a844af18acdffa9")
}
> db.performQueryDemo.insertOne({"PlayerDetails":{"PlayerScore":0,"PlayerLevel":1},"PlayerName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ebbb1a844af18acdffaa")
}
> db.performQueryDemo.insertOne({"PlayerDetails":{"PlayerScore":-10,"PlayerLevel":0},"PlayerName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ebd41a844af18acdffab")
}
> db.performQueryDemo.insertOne({"PlayerDetails":{"PlayerScore":1,"PlayerLevel":1},"PlayerName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ebe31a844af18acdffac")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd7eba41a844af18acdffa9"),
   "PlayerDetails" : {
      "PlayerScore" : 1000,
      "PlayerLevel" : 2
   },
   "PlayerName" : "Chris"
}
{
   "_id" : ObjectId("5cd7ebbb1a844af18acdffaa"),
   "PlayerDetails" : {
      "PlayerScore" : 0,
      "PlayerLevel" : 1
   },
   "PlayerName" : "Robert"
}
{
   "_id" : ObjectId("5cd7ebd41a844af18acdffab"),
   "PlayerDetails" : {
      "PlayerScore" : -10,
      "PlayerLevel" : 0
   },
   "PlayerName" : "Larry"
}
{
   "_id" : ObjectId("5cd7ebe31a844af18acdffac"),
   "PlayerDetails" : {
      "PlayerScore" : 1,
      "PlayerLevel" : 1
   },
   "PlayerName" : "David"
}

Following is the query to perform $gt on a hash in a MongoDB document. Here, we will get the records of the players with score more than 0 −

> db.performQueryDemo.find({"PlayerDetails.PlayerScore":{$gt:0}});

This will produce the following output −

{ "_id" : ObjectId("5cd7eba41a844af18acdffa9"), "PlayerDetails" : { "PlayerScore" : 1000, "PlayerLevel" : 2 }, "PlayerName" : "Chris" }

{ "_id" : ObjectId("5cd7ebe31a844af18acdffac"), "PlayerDetails" : { "PlayerScore" : 1, "PlayerLevel" : 1 }, "PlayerName" : "David" }

Advertisements

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