[MongoDB]: Escaping single quotes in a document’ field’s value while querying

When you’ve data in a collection with quotes and different case (lower/upper) and you wanted retrieve all of them with a single query – there are various ways to do that. Let’s see few of them in the below illustration.

www:bin dbversity$ pwd
/Users/dbversity/mongodb-osx-x86_64-4.0.2/bin
www:bin dbversity$
www:bin dbversity$ mkdir -p data log 
www:bin dbversity$ 
www:bin dbversity$ ./mongod –dbpath ./data/ –logpath ./log/mongod.log –port 27017 –fork 
2018-11-27T22:49:12.755+0530 I CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify –sslDisabledProtocols ‘none’
about to fork child process, waiting until server is ready for connections.
forked process: 4744
child process started successfully, parent exiting
www:bin dbversity$ 
www:bin dbversity$ ./mongo –quiet 
>  
> use mydb 
switched to db mydb

> db.merchants.insert({_id:1, name: “Orhi’s” })
WriteResult({ “nInserted” : 1 })

> db.merchants.insert({_id:2, name: “Orhis” })
WriteResult({ “nInserted” : 1 })

> db.merchants.insert({_id:3, name: “orhis” })
WriteResult({ “nInserted” : 1 })

> db.merchants.insert({_id:4, name: “orhi’s” })
WriteResult({ “nInserted” : 1 })
> 

Now, you just want to query all the Orhi’s merchants regardless the quotes in there and case lower/upper.

> db.merchants.find()

{ “_id” : 1, “name” : “Orhi’s” }
{ “_id” : 2, “name” : “Orhis” }
{ “_id” : 3, “name” : “orhis” }
{ “_id” : 4, “name” : “orhi’s” }


> db.merchants.find( { name: /^orhi/i  } )
{ “_id” : 1, “name” : “Orhi’s” }
{ “_id” : 2, “name” : “Orhis” }
{ “_id” : 3, “name” : “orhis” }
{ “_id” : 4, “name” : “orhi’s” }

db.merchants.find( { name: /orhi.*/i  } )
{ “_id” : 1, “name” : “Orhi’s” }
{ “_id” : 2, “name” : “Orhis” }
{ “_id” : 3, “name” : “orhis” }
{ “_id” : 4, “name” : “orhi’s” }

> // Alternatively – try text search as well

db.merchants.createIndex({ name: ‘text’ })
{
“createdCollectionAutomatically” : false,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1
}

> db.merchants.find( { $text: { $search: “orhis” } } )
{ “_id” : 4, “name” : “orhi’s” }
{ “_id” : 3, “name” : “orhis” }
{ “_id” : 2, “name” : “Orhis” }
{ “_id” : 1, “name” : “Orhi’s” }


  • Ask Question