| by Arround The Web | No comments

How to Query Embedded Documents with MongoDB ElemMatch

When querying records with arrays, including nested or sub-fields, the $elemMatch operator in MongoDB is a potent utility. It enables you to declare a set of requirements that a minimum of a single component in an array field of a record must meet. This is very helpful when you filter or extract records from a complicated data set using a particular set of constraints. Whenever you have a list of integrated records and are looking through the list of records that meet certain criteria, this is helpful. Therefore, we will be discussing its use with the help of query code examples.

Create Collection

Starting with this guide, we should have a collection with some nested fields. Therefore, we prefer to create a new collection named “Movie” that will contain the data regarding the movie types and the main actors that suit the type. We have added a total of 4 main records with the fields _id, type (of the movie), and “actor”. Each “actor” field in every document contains an array of two records.

Each of the records of the array contains 2 fields inside i.e. name and age. This way, the collection contains the data of 2 actors for each type of movie. The insertMany() function has been executed to insert these records and the acknowledgment has been displayed by the MongoDB.

db.Movie.insertMany([

{ "_id": 1, "type": "Comedy",

"actor": [ { "name": "Ken", "age": 40 }, { "name": "Cillian", "age": 40 } ] },

{ "_id": 2, "type": "Fiction",

"actor": [ { "name": "Ken", "age": 35 }, { "name": "Robert", "age": 29 } ] },

{ "_id": 3, "type": "Suspense",

"actor": [ { "name": "Cillian", "age": 30 }, { "name": "Ema", "age": 32 } ] },

{ "_id": 4, "type": "Melo-Drama",

"actor": [ { "name": "R.D", "age": 44 }, { "name": "William", "age": 37 } ] } ]);

Although the acknowledgment has been displayed, we must reassure ourselves that the records we have added are correct according to our personal preferences. So, MongoDB’s find() function is handy to check the collection records. The output of the Movie collection has been showing all four records on the MongoDB shell screen.

db.Movie.find()

Example 01: elemMatch on Single Field

Let’s move towards applying the elemMatch operator on the collection fields. For this, we will be starting with the single-field constraint. Thus, the elemMatch() operator has been applied to the sub-field “name” of the column “actor”. The condition says that there should be one name, “ken” in all the output records.

The elemMatch() operator has been applied with the help of the find() function. The output for this query searches the whole collection for the name “ken” in the “actor” field and returns the specific record. Therefore, a total of 2 records have been found where the name field of the “actor” field is “ken”. It doesn’t matter if the other record of the array-field “actor” has some other names like “Cillian” and “Robert”.

db.Movie.find({ "actor": { $elemMatch: { "name": "Ken" } } })

We have applied the emenMatch operator in the above illustration to the name field. Now, we can also apply the elemMatch operator to other fields like “age”. Here, you can add the exact value of the field “age” or use the logical operators i.e. greater than, less than.

Therefore, we have been using the $gt (greater than) operator to search for the records in the “Movie” collection where the array-field “actor” has a greater than “35” value in its “age” sub-field. The returned result contains two records with the “age” subfield containing greater than 35 values.

db.Movie.find({ "actor": { $elemMatch: { "age": { $gt: 35 } } } })

Example 02: elemMatch on Multiple Fields

The above illustration depicts the use of the elemMatch operator on the single fields of any array-like field in a straightforward way. But you can also apply the elemMatch operator of MongoDB on the multiple fields of the array-like fields. Therefore, we will use it on a new query containing the “find()” function. This find() function has been applied to the array-type “actor” field of the “Movie” collection.

After this, the elemMatch approaches have been applied to the “name” and “age” fields. There is a need to understand that this time the elemMatch operator has been restricting the search by applying strict constraints i.e. as the name has been set to “Cillian” and the “age” field should have a value greater than “30” via the $gt (greater than) operator usage here. The only records of the Movie collection will be outputted where the possibility of an “actor” column with “name” Cillian” and “age” greater than 30 within one of its embedded documents. If any record missed at least one of the specified conditions, that record will be ignored completely.

Therefore, 3 of the collection records have been ignored even though they have one record that satisfies one of the conditions specified in the “elemMatch” query, and only a single record (_id: 1) has been displayed on our shell screen. This record contains the name “Cillian” in one of its records while the age “40” is within both the embedded records.

db.Movie.find({ "actor": { $elemMatch: { "name": "Cillian", "age": { $gt: 30 } } } })

Example 03: elemMatch on Multiple Conditions

You can also try the elemMatch operator on the same field with multiple conditions. For instance, we have been applying it to the “name” field embedded in the “actor” field of the collection “Movie”. This time, we will search for the records named “Ken” and “Cillian”. Any of the records with the value “ken” or “Cillian” in the name field will be output. For this, we have applied the elemMatch operator to two expressions. The output of this query has been displaying two records, i.e., one with both specified values and the other with one match value.

db.Movie.find({ "actor": { $elemMatch: { "name": "Ken" } }, "actor": { $elemMatch: { "name": "Cillian" } } })

Similarly, you can utilize $ and $or logical operators on the queries holding the elemMatch operator. The illustrations below show the use of $or operators in a query using the same conditions on the “name” field. The result returns three records.

db.Movie.find({ "actor": { $elemMatch: { $or: [ { "name": "Ken" }, { "name": "Cillian" } ] } } })

Conclusion

The robust search operator $elemMatch in MongoDB may be employed to locate records that include arrays and to impose specific requirements on the members of those arrays. Within the provided query examples in this guide, the $elemMatch operation ensures that the identical array component satisfies all provided constraints when searching embedded records inside arrays.

Share Button

Source: linuxhint.com

Leave a Reply