Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Is it possible to cast in a MongoDB Query?
Yes, it is possible to cast in a MongoDB query −
db.yourCollectionName.find("this.yourFieldName >yourValue);
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.castingDemo.insertOne({"Amount":"200"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c947e874cf1f7a64fa4df42")
}
> db.castingDemo.insertOne({"Amount":"100"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c947e8e4cf1f7a64fa4df43")
}
> db.castingDemo.insertOne({"Amount":"110"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c947e944cf1f7a64fa4df44")
}
> db.castingDemo.insertOne({"Amount":"95"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c947e9d4cf1f7a64fa4df45")
}
> db.castingDemo.insertOne({"Amount":"85"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c947ea44cf1f7a64fa4df46")
}
> db.castingDemo.insertOne({"Amount":"75"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c947ebd4cf1f7a64fa4df47")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.castingDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c947e874cf1f7a64fa4df42"), "Amount" : "200" }
{ "_id" : ObjectId("5c947e8e4cf1f7a64fa4df43"), "Amount" : "100" }
{ "_id" : ObjectId("5c947e944cf1f7a64fa4df44"), "Amount" : "110" }
{ "_id" : ObjectId("5c947e9d4cf1f7a64fa4df45"), "Amount" : "95" }
{ "_id" : ObjectId("5c947ea44cf1f7a64fa4df46"), "Amount" : "85" }
{ "_id" : ObjectId("5c947ebd4cf1f7a64fa4df47"), "Amount" : "75" }
Here is the query that automatically converts from string to number −
> db.castingDemo.find("this.Amount > 85");
The following is the output −
{ "_id" : ObjectId("5c947e874cf1f7a64fa4df42"), "Amount" : "200" }
{ "_id" : ObjectId("5c947e8e4cf1f7a64fa4df43"), "Amount" : "100" }
{ "_id" : ObjectId("5c947e944cf1f7a64fa4df44"), "Amount" : "110" }
{ "_id" : ObjectId("5c947e9d4cf1f7a64fa4df45"), "Amount" : "95" } Advertisements
