要按几个数组元素过滤,请使用$elemMatch。让我们创建一个包含文档的集合-
> db.demo87.insertOne( ... { ... id:101, ... "Details": [ ... { ... "EmployeeName": "Chris", ... "Salary": 45000 ... }, ... { ... "EmployeeName": "David", ... "Salary": 50000 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2c113871bf0181ecc422ab") } > db.demo87.insertOne( ... { ... id:102, ... "Details": [ ... { ... "EmployeeName": "Chris", ... "Salary": 65000 ... }, ... { ... "EmployeeName": "Mike", ... "Salary": 100000 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2c114371bf0181ecc422ac") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo87.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2c113871bf0181ecc422ab"), "id" : 101, "Details" : [ { "EmployeeName" : "Chris", "Salary" : 45000 }, { "EmployeeName" : "David", "Salary" : 50000 } ] } { "_id" : ObjectId("5e2c114371bf0181ecc422ac"), "id" : 102, "Details" : [ { "EmployeeName" : "Chris", "Salary" : 65000 }, { "EmployeeName" : "Mike", "Salary" : 100000 } ] }
以下是按几个数组元素过滤的查询-
> db.demo87.find({ Details: { $elemMatch: { "EmployeeName": 'Chris', "Salary": 65000 }}});
这将产生以下输出-
{ "_id" : ObjectId("5e2c114371bf0181ecc422ac"), "id" : 102, "Details" : [ { "EmployeeName" : "Chris", "Salary" : 65000 }, { "EmployeeName" : "Mike", "Salary" : 100000 } ] }