You can use $or operator along with limit(1) to match element in array. Let us first create a collection with documents −
> db.matchElementInArrayDemo.insertOne( ... { ... "StudentName" : "Chris" , ... "StudentOtherDetails" : ... [ ... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"}, ... {"StudentCountryName" : "UK" , "StudentSkills" : "Java"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd423282cba06f46efe9ee2") } > db.matchElementInArrayDemo.insertOne( ... { ... "StudentName" : "Chris" , ... "StudentOtherDetails" : ... [ ... {"StudentCountryName" : "AUS" , "StudentSkills" : "PHP"}, ... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd423412cba06f46efe9ee3") }
Following is the query to display all documents from a collection with the help of find() method −
> db.matchElementInArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] } { "_id" : ObjectId("5cd423412cba06f46efe9ee3"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "AUS", "StudentSkills" : "PHP" }, { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" } ] }
Here is the query to match element in array of MongoDB −
> db.matchElementInArrayDemo.find( { $or : [ {"StudentOtherDetails.StudentCountryName": "US" } ,{"StudentOtherDetails.StudentSkills": "MongoDB" } ] } ).limit(1);
This will produce the following output −
{ "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] }