Fix: MongoDB Robomongo: db.data.find(…).collation is not a function?


The collation introduced in version MongoDB 3.4. Maybe, you implemented collation in a previous version.

For our example, we are using MongoDB version 4.0.5. Following is the query to check the current version on system −

> db.version()

This will produce the following output −

4.0.5

Let us first create a collection with documents −

> db.collationExample.createIndex({Value: 1}, {collation: {locale: "en", strength: 1}});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.collationExample.insertOne({'Value':'x'});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038a3cf5e889d7a51994f5")
}
> db.collationExample.insertOne({'Value':'X'});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038a48f5e889d7a51994f6")
}
> db.collationExample.insertOne({'Value':'Y'});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038a49f5e889d7a51994f7")
}
> db.collationExample.insertOne({'Value':'a'});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038a49f5e889d7a51994f8")
}
> db.collationExample.insertOne({'Value':'á'});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038a4bf5e889d7a51994f9")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.collationExample.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5e038a3cf5e889d7a51994f5"), "Value" : "x" }
{ "_id" : ObjectId("5e038a48f5e889d7a51994f6"), "Value" : "X" }
{ "_id" : ObjectId("5e038a49f5e889d7a51994f7"), "Value" : "Y" }
{ "_id" : ObjectId("5e038a49f5e889d7a51994f8"), "Value" : "a" }
{ "_id" : ObjectId("5e038a4bf5e889d7a51994f9"), "Value" : "á" }

Here is the query to use COLLATION() −

> db.collationExample.find({ Value: "a" } ).collation( { locale: "en", strength: 1 } );

This will produce the following output −

{ "_id" : ObjectId("5e038a49f5e889d7a51994f8"), "Value" : "a" }
{ "_id" : ObjectId("5e038a4bf5e889d7a51994f9"), "Value" : "á" }

Updated on: 27-Mar-2020

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements