How to query MongoDB with “like”?

MongoDBDatabaseBig Data Analytics

You can easily query MongoDB with “like”:

db.yourCollectionName.find({"yourFieldName" : /.*yourMatchingValue.*/}).pretty();

To understand the above syntax, let us create a collection with some documents. Here, we have a collection with the name ‘employee’. The query is as follows:

> db.employee.insert({"EmployeeName":"John","EmployeeSalary":450000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"Carol","EmployeeSalary":150000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"James","EmployeeSalary":550000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"Jace","EmployeeSalary":670000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"Larry","EmployeeSalary":1000000});
WriteResult({ "nInserted" : 1 })

Now you can display all documents from a collection using find() method. The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6c0b2e68174aae23f5ef59"),
   "EmployeeName" : "John",
   "EmployeeSalary" : 450000
}
{
   "_id" : ObjectId("5c6c0b3b68174aae23f5ef5a"),
   "EmployeeName" : "Carol",
   "EmployeeSalary" : 150000
}
{
   "_id" : ObjectId("5c6c0b4768174aae23f5ef5b"),
   "EmployeeName" : "James",
   "EmployeeSalary" : 550000
}
{
   "_id" : ObjectId("5c6c0b8f68174aae23f5ef5c"),
   "EmployeeName" : "Jace",
   "EmployeeSalary" : 670000
}
{
   "_id" : ObjectId("5c6c0b9e68174aae23f5ef5d"),
   "EmployeeName" : "Larry",
   "EmployeeSalary" : 1000000
}

Here is the query in MongoDB with “like” operator:

> db.employee.find({"EmployeeName":/.*J.*/}).pretty();

The following is the output:

{
   "_id" : ObjectId("5c6c0b2e68174aae23f5ef59"),
   "EmployeeName" : "John",
   "EmployeeSalary" : 450000
}
{
   "_id" : ObjectId("5c6c0b4768174aae23f5ef5b"),
   "EmployeeName" : "James",
   "EmployeeSalary" : 550000
}
{
   "_id" : ObjectId("5c6c0b8f68174aae23f5ef5c"),
   "EmployeeName" : "Jace",
   "EmployeeSalary" : 670000
}
raja
Published on 18-Mar-2019 15:34:24
Advertisements