如何在 MongoDB 中匹配数组中的多个条件?
要匹配数组中的多个条件,请使用 aggregate()。让我们创建一个包含文档的集合 -
> db.demo84.insertOne({ ... "EmployeeDetails": [ ... {Name: 'John', Salary:45000, isMarried: true}, ... {Name: 'Chris', Salary:50000, isMarried: false} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2c0a3471bf0181ecc422a5") } > db.demo84.insertOne({ ... "EmployeeDetails": [ ... {Name: 'Sam', Salary:56000, isMarried: false}, ... {Name: 'Bob', Salary:50000, isMarried: false} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2c0a4071bf0181ecc422a6") }
使用 find() 方法从集合中显示所有文档 -
> db.demo84.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e2c0a3471bf0181ecc422a5"), "EmployeeDetails" : [ { "Name" : "John", "Salary" : 45000, "isMarried" : true }, { "Name" : "Chris", "Salary" : 50000, "isMarried" : false } ] } { "_id" : ObjectId("5e2c0a4071bf0181ecc422a6"), "EmployeeDetails" : [ { "Name" : "Sam", "Salary" : 56000, "isMarried" : false }, { "Name" : "Bob", "Salary" : 50000, "isMarried" : false } ] }
以下是匹配数组中的多个条件的查询 -
示例
> db.demo84.aggregate( ... { "$match": { ... "EmployeeDetails": { ... "$elemMatch": { ... "Name": "Chris", ... "isMarried": false ... } ... } ... }} ... );
这将产生以下输出 -
{ "_id" : ObjectId("5e2c0a3471bf0181ecc422a5"), "EmployeeDetails" : [ { "Name" : "John", "Salary" : 45000, "isMarried" : true }, { "Name" : "Chris", "Salary" : 50000, "isMarried" : false } ] }
广告