Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to perform $gt on a hash in a MongoDB document?
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