为此,请将聚合框架与$elemMatch运算符配合使用。首先让我们创建一个包含文档的集合-
> db.matchMultipleCriteriaDemo.insertOne({ "EmployeeDetails": [ {"EmployeeName": "Chris", "Salary": 45000, "Language":"Java"}, {"EmployeeName": "Robert", "Salary": 41000, "Language":"Python"} ] }); { "acknowledged" : true, "insertedId" : ObjectId("5cea3bf0ef71edecf6a1f689") } > db.matchMultipleCriteriaDemo.insertOne({ "EmployeeDetails": [ {"EmployeeName": "David", "Salary": 55000, "Language":"C++"}, {"EmployeeName": "Bob", "Salary": 61000, "Language":"C"} ] }); { "acknowledged" : true, "insertedId" : ObjectId("5cea3bf1ef71edecf6a1f68a") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.matchMultipleCriteriaDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cea3bf0ef71edecf6a1f689"), "EmployeeDetails" : [ { "EmployeeName" : "Chris", "Salary" : 45000, "Language" : "Java" }, { "EmployeeName" : "Robert", "Salary" : 41000, "Language" : "Python" } ] } { "_id" : ObjectId("5cea3bf1ef71edecf6a1f68a"), "EmployeeDetails" : [ { "EmployeeName" : "David", "Salary" : 55000, "Language" : "C++" }, { "EmployeeName" : "Bob", "Salary" : 61000, "Language" : "C" } ] }
以下是匹配数组中多个条件的查询-
> db.matchMultipleCriteriaDemo.aggregate({ "$match": { "EmployeeDetails": { "$elemMatch": { "EmployeeName": "Bob", "Language":"C" } } }} ).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cea3bf1ef71edecf6a1f68a"), "EmployeeDetails" : [ { "EmployeeName" : "David", "Salary" : 55000, "Language" : "C++" }, { "EmployeeName" : "Bob", "Salary" : 61000, "Language" : "C" } ] }