为此,可以使用$elemMatch运算符。$elemMatch运算符匹配包含一个数组字段的文档,该数组字段的至少一个元素与所有指定的查询条件匹配。首先让我们创建一个包含文档的集合-
> db.filterBySeveralElementsDemo.insertOne( "_id":100, "StudentDetails": [ { "StudentName": "John", "StudentCountryName": "US", }, { "StudentName": "Carol", "StudentCountryName": "UK" } ] } ); { "acknowledged" : true, "insertedId" : 100 } > db.filterBySeveralElementsDemo.insertOne( { "_id":101, "StudentDetails": [ { "StudentName": "Sam", "StudentCountryName": "AUS", }, { "StudentName": "Chris", "StudentCountryName": "US" } ] } ); { "acknowledged" : true, "insertedId" : 101 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.filterBySeveralElementsDemo.find().pretty();
这将产生以下输出-
{ "_id" : 100, "StudentDetails" : [ { "StudentName" : "John", "StudentCountryName" : "US" }, { "StudentName" : "Carol", "StudentCountryName" : "UK" } ] } { "_id" : 101, "StudentDetails" : [ { "StudentName" : "Sam", "StudentCountryName" : "AUS" }, { "StudentName" : "Chris", "StudentCountryName" : "US" } ] }
以下是按几个数组元素过滤的查询-
> db.filterBySeveralElementsDemo.find({ StudentDetails: { $elemMatch: { StudentName: 'Sam', StudentCountryName: 'AUS' }}}).pretty();
这将产生以下输出-
{ "_id" : 101, "StudentDetails" : [ { "StudentName" : "Sam", "StudentCountryName" : "AUS" }, { "StudentName" : "Chris", "StudentCountryName" : "US" } ] }