Syntax error Sort MongoDB field which contains both integer and decimal values?

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 }
Updated on: 2020-07-01T06:42:25+05:30

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements