Query MongoDB with “like” implementation on name and email field beginning with a specific letter?

MongoDBDatabaseBig Data Analytics

For “like” implementation in MongoDB, use / / and set that specific letter in between. For example −

/J/

Let us create a collection with documents −

> db.demo554.insertOne({"UserName":"John","UserMailId":"John@gmail.com"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f1cfed1d72c4545cb8679")
}
> db.demo554.insertOne({"UserName":"Chris","UserMailId":"Chris@gmail.com"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f1d0cd1d72c4545cb867a")
}
> db.demo554.insertOne({"UserName":"Jace","UserMailId":"Jace@gmail.com"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f1d1cd1d72c4545cb867b")
}

Display all documents from a collection with the help of find() method −

> db.demo554.find();

This will produce the following output −

{ "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "John@gmail.com" }
{ "_id" : ObjectId("5e8f1d0cd1d72c4545cb867a"), "UserName" : "Chris", "UserMailId" : "Chris@gmail.com" }
{ "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "Jace@gmail.com" }

Following is the query to implementation of “like” −

> db.demo554.find({
...    "$or": [
...       { "UserName": /J/ },
...
...       { "UserMailId": /J/ }
...    ]
... }
... );

This will produce the following output −

{ "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "John@gmail.com" }
{ "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "Jace@gmail.com" }
raja
Published on 14-May-2020 11:30:45
Advertisements