MongoDB如何查询嵌套数组并仅投影匹配的数组项?
MongoDB查询特定客户端下符合条件的员工数据
数据结构
[ { "clientName": "client1", "employees": [ { "employeename": 1, "configuration": { "isAdmin": true, "isManager": false } }, { "employeename": 2, "configuration": { "isAdmin": false, "isManager": false } } ] }, { // 其他客户端数据 } ]
问题需求
已知客户端名称,需查询该客户端内是管理员的员工,且仅返回匹配的员工数据。同时想了解如何组合多条件查询(比如筛选既是管理员又是经理的员工)。
尝试过的无效语句
db.collection.find( {clientName: "client1", "employees.configuration.isAdmin": true}, {"employees.employeename": 1} )
执行后返回了该客户端下的所有员工,使用$elemMatch也未得到预期结果。
解决方案
1. 查询特定客户端下的管理员员工(推荐用聚合管道)
聚合管道的$filter操作符可以精准筛选数组中所有符合条件的元素,完整语句如下:
db.collection.aggregate([ // 先匹配目标客户端,缩小查询范围 { $match: { clientName: "client1" } }, // 筛选employees数组中isAdmin为true的员工 { $project: { employees: { $filter: { input: "$employees", cond: { $eq: ["$$this.configuration.isAdmin", true] } } }, _id: 0 // 不需要_id字段可添加此配置 } } ])
2. 查询既是管理员又是经理的员工
只需修改$filter的条件为多条件组合,用$and连接即可:
db.collection.aggregate([ { $match: { clientName: "client1" } }, { $project: { employees: { $filter: { input: "$employees", cond: { $and: [ { $eq: ["$$this.configuration.isAdmin", true] }, { $eq: ["$$this.configuration.isManager", true] } ] } } }, _id: 0 } } ])
3. 局限性方案:find结合$elemMatch投影
如果只需要返回数组中第一个符合条件的员工,可以用这个方法,但无法返回所有匹配项:
db.collection.find( { clientName: "client1" }, { employees: { $elemMatch: { "configuration.isAdmin": true } }, _id: 0 } )
原尝试无效的原因
- 直接在
find的查询条件中添加"employees.configuration.isAdmin": true,只会筛选出包含至少一个管理员的客户端文档,但投影"employees.employeename": 1会返回整个employees数组,不会过滤其中的元素。 $elemMatch在投影中使用时,默认仅返回数组里第一个符合条件的元素,无法返回所有匹配的员工,因此不符合需求。
内容的提问来源于stack exchange,提问作者Husain Shaikh
相关产品推荐
相关产品推荐

