您可以将$or运算符与limit(1)一起使用以匹配数组中的元素。首先让我们创建一个包含文档的集合-
> 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") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.matchElementInArrayDemo.find().pretty();
这将产生以下输出-
{ "_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" } ] }
这是匹配MongoDB数组中的元素的查询-
> db.matchElementInArrayDemo.find( { $or : [ {"StudentOtherDetails.StudentCountryName": "US" } ,{"StudentOtherDetails.StudentSkills": "MongoDB" } ] } ).limit(1);
这将产生以下输出-
{ "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] }