Mongoose按operatorName与嵌套users.email查询无效问题求助
解决Mongoose嵌套数组多条件筛选问题
问题根源
你的查询能正确筛选出匹配operatorName且包含指定email用户的Operator文档,但MongoDB默认会返回文档的完整users数组,不会自动过滤数组中不符合条件的元素,所以你会看到该operator下的所有用户数据。
方案一:用find结合投影(仅返回第一个匹配的数组元素)
通过投影中的$elemMatch指定只返回users数组中符合email条件的第一个元素:
Operators.find( { operatorName: operatorName, 'users.email': 'super@m.com' }, { operatorName: 1, 'users': { $elemMatch: { email: 'super@m.com' } } }, function (err, docs) { if (err) console.log(err); else { docs.forEach(data => console.log(data)); // res.render('total_earns_operator_tables', { operators: docs }); } } );
方案二:用aggregate聚合查询(返回所有匹配的数组元素)
如果需要保留users数组中所有符合email条件的元素,使用$filter在聚合的$project阶段过滤数组,这是更高效简洁的方式:
Operators.aggregate([ { $match: { operatorName: operatorName, 'users.email': 'demouser@mail.com' }}, { $project: { operatorName: 1, users: { $filter: { input: '$users', cond: { $eq: ['$$this.email', 'demouser@mail.com'] } } } }} ], function (err, docs) { if (err) console.log(err); else { docs.forEach(data => console.log(data)); // res.render('total_earns_operator_tables', { operators: docs }); } });
额外提示
- 原始查询中的
$and是冗余的,MongoDB默认将多个查询条件视为逻辑与,直接写{ operatorName: operatorName, 'users.email': 'xxx' }即可。 - 若用
$unwind+$match+$group的组合也能实现,但$filter的性能更优,代码更简洁。
内容的提问来源于stack exchange,提问作者hobik
相关产品推荐
相关产品推荐

