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
Sort MongoDB field which contains both integer and decimal values?
To sort, use sort() in MongoDB. Let us create a collection with documents −
> db.demo755.insertOne({"Value":10});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae9e72a930c785c834e572")
}
> db.demo755.insertOne({"Value":10.5});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae9e75a930c785c834e573")
}
> db.demo755.insertOne({"Value":9.5});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae9e79a930c785c834e574")
}
> db.demo755.insertOne({"Value":12.5});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae9e7fa930c785c834e575")
}
> db.demo755.insertOne({"Value":11.5});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae9e87a930c785c834e576")
}
> db.demo755.insertOne({"Value":6});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae9e97a930c785c834e577")
}
Display all documents from a collection with the help of find() method −
> db.demo755.find();
This will produce the following output −
{ "_id" : ObjectId("5eae9e72a930c785c834e572"), "Value" : 10 }
{ "_id" : ObjectId("5eae9e75a930c785c834e573"), "Value" : 10.5 }
{ "_id" : ObjectId("5eae9e79a930c785c834e574"), "Value" : 9.5 }
{ "_id" : ObjectId("5eae9e7fa930c785c834e575"), "Value" : 12.5 }
{ "_id" : ObjectId("5eae9e87a930c785c834e576"), "Value" : 11.5 }
{ "_id" : ObjectId("5eae9e97a930c785c834e577"), "Value" : 6 }
Following is the query to sort MongoDB field which contains both integer and decimal −
> db.demo755.find().sort({Value:1});
This will produce the following output −
{ "_id" : ObjectId("5eae9e97a930c785c834e577"), "Value" : 6 }
{ "_id" : ObjectId("5eae9e79a930c785c834e574"), "Value" : 9.5 }
{ "_id" : ObjectId("5eae9e72a930c785c834e572"), "Value" : 10 }
{ "_id" : ObjectId("5eae9e75a930c785c834e573"), "Value" : 10.5 }
{ "_id" : ObjectId("5eae9e87a930c785c834e576"), "Value" : 11.5 }
{ "_id" : ObjectId("5eae9e7fa930c785c834e575"), "Value" : 12.5 } Advertisements
