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
-
Economics & Finance
Selected Reading
Sort MongoDB field which contains both integer and decimal values?
To sort a MongoDB field containing both integer and decimal values, use the sort() method. MongoDB automatically handles mixed numeric types (integers and decimals) in the same field and sorts them by their numeric value.
Syntax
db.collection.find().sort({fieldName: 1}); // 1 for ascending, -1 for descending
Sample Data
db.demo755.insertMany([
{"Value": 10},
{"Value": 10.5},
{"Value": 9.5},
{"Value": 12.5},
{"Value": 11.5},
{"Value": 6}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5eae9e72a930c785c834e572"),
ObjectId("5eae9e75a930c785c834e573"),
ObjectId("5eae9e79a930c785c834e574"),
ObjectId("5eae9e7fa930c785c834e575"),
ObjectId("5eae9e87a930c785c834e576"),
ObjectId("5eae9e97a930c785c834e577")
]
}
Display Documents
db.demo755.find();
{ "_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 }
Example: Sort in Ascending Order
db.demo755.find().sort({Value: 1});
{ "_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 }
Example: Sort in Descending Order
db.demo755.find().sort({Value: -1});
{ "_id" : ObjectId("5eae9e7fa930c785c834e575"), "Value" : 12.5 }
{ "_id" : ObjectId("5eae9e87a930c785c834e576"), "Value" : 11.5 }
{ "_id" : ObjectId("5eae9e75a930c785c834e573"), "Value" : 10.5 }
{ "_id" : ObjectId("5eae9e72a930c785c834e572"), "Value" : 10 }
{ "_id" : ObjectId("5eae9e79a930c785c834e574"), "Value" : 9.5 }
{ "_id" : ObjectId("5eae9e97a930c785c834e577"), "Value" : 6 }
Conclusion
MongoDB's sort() method seamlessly handles fields containing both integers and decimals, sorting them by their numeric value regardless of type. Use 1 for ascending and -1 for descending order.
Advertisements
