使用 MongoDB 匹配数组中的多个条件?
为此,请连同 $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" } ] }
广告