Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb sort with case insensitive manner

I am struct very hard at one project in nodejs(express) with mongodb as database. When i get all data using sort() it returns data in wrong manner, so is there way to get it properly format as i am expecting as below: If we have three record in DB:

---------------------
id  | Name |  aga
---------------------
1   | atul | 21
---------------------
2   | Bhavik | 22
---------------------
3   | Jay | 25

What i am getting at present is:

2,3,1 series data

What i expect is to come is: 1,2,3

It means is to ignore the case while sorting is it possible without adding new column.

like image 937
Rushabh Madhu Avatar asked Aug 25 '18 09:08

Rushabh Madhu


People also ask

How do I sort a case insensitive in MongoDB?

This means the only way to sort case insensitive currently is to actually create a specific "lower cased" field, copying the value (lower cased of course) of the sort field in question and sorting on that instead.

Are MongoDB collections case sensitive?

MongoDB Collection is case sensitive: It is totally valid for one database to have two collections: Hello , and hello , while Presto-MongoDB Connector use SchemaTableName to represent collection name, SchemaTableName itself is not case sensitive, it causes that we can not query mongodb collection which have uppercase ...

How do I sort alphabetically in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Does MongoDB support sorting?

MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted.


2 Answers

You need to use collation here with locale: "en"

db.collection.find({}).collation({ locale: "en" }).sort({ name: 1 })

So for the below document

{ "_id" : 1, "name" : "Bhavik" }
{ "_id" : 2, "name" : "Jay" }
{ "_id" : 3, "name" : "atul" }

You will get

{ "_id" : 3, "name" : "atul" }
{ "_id" : 1, "name" : "Bhavik" }
{ "_id" : 2, "name" : "Jay" }
like image 76
Ashh Avatar answered Oct 25 '22 18:10

Ashh


Create the collection with a default collation by this way you can order by any property with case insensitive.

db.createCollection("collection_name", { collation: { locale: 'en_US', strength: 2 } } )

db.getCollection('collection_name').find({}).sort( { 'property_name': -1 } )

More info: https://docs.mongodb.com/manual/core/index-case-insensitive/

like image 20
perezmlal Avatar answered Oct 25 '22 18:10

perezmlal