MongoDB query to find multiple matchings inside array of objects?

MongoDBDatabaseBig Data Analytics

For this, use $and along with $regex. The $and performs a logical AND operation on an array of one or more expressions and selects the documents that satisfy all the expressions in the array.

Let us create a collection with documents −

> db.demo525.insertOne({"details":[{Name:"Chris","CountryName":"US"}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8ae5ef437efc8605595b66")
}
> db.demo525.insertOne({"details":[{Name:"Bob","CountryName":"UK"}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8ae5f8437efc8605595b67")
}
> db.demo525.insertOne({"details":[{Name:"chris","CountryName":"us"}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8ae602437efc8605595b68")
}
> db.demo525.insertOne({"details":[{Name:"Mike","CountryName":"UK"}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8ae60b437efc8605595b69")
}

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

> db.demo525.find();

This will produce the following output −

{ "_id" : ObjectId("5e8ae5ef437efc8605595b66"), "details" : [ { "Name" : "Chris", "CountryName" : "US" } ] }
{ "_id" : ObjectId("5e8ae5f8437efc8605595b67"), "details" : [ { "Name" : "Bob", "CountryName": "UK" } ] }
{ "_id" : ObjectId("5e8ae602437efc8605595b68"), "details" : [ { "Name" : "chris","CountryName" : "us" } ] }
{ "_id" : ObjectId("5e8ae60b437efc8605595b69"), "details" : [ { "Name" : "Mike","CountryName" : "UK" } ] }

Following is the query to find multiple matchings inside an array of objects −

> db.demo525.find(
... {"$and": [
...    { "details" : { "$elemMatch" :{ "Name": {$regex: new RegExp('^' + 'Chris', 'i')}}} },
...    { "details" : { "$elemMatch" :{ "CountryName": {$regex: new RegExp('^' + 'us', 'i')}}}
}
... ]}
... )

This will produce the following output −

{ "_id" : ObjectId("5e8ae5ef437efc8605595b66"), "details" : [ { "Name" : "Chris", "CountryName" : "US" } ] }
{ "_id" : ObjectId("5e8ae602437efc8605595b68"), "details" : [ { "Name" : "chris", "CountryName" : "us" } ] }
raja
Published on 13-May-2020 07:31:30
Advertisements