如何在MongoDB中查询匹配多组指定字段组合条件的文档?
MongoDB多组合条件匹配查询方案
你需要同时匹配多组userId+userName的组合,只要满足其中任意一组条件的文档都要返回,需使用$or操作符实现,不能直接给find方法传入数组作为查询条件。
现有集合结构
{ "_id": "1", "userId": "2", "userName": "A" } { "_id": "2", "userId": "3", "userName": "B" } { "_id": "4", "userId": "5", "userName": "C" } { "_id": "6", "userId": "7", "userName": "D" }
正确查询语句
db.users.find({ $or: [ { "userId": "2", "userName": "A" }, { "userId": "3", "userName": "B" }, { "userId": "5", "userName": "C" } ] })
返回结果
执行上述查询后得到的结果和预期完全一致:
{ "_id": "1", "userId": "2", "userName": "A" } { "_id": "2", "userId": "3", "userName": "B" } { "_id": "4", "userId": "5", "userName": "C" }
语法说明
- MongoDB的
find方法第一个参数接收查询条件对象,不支持直接传入数组 $or操作符接收条件数组,只要文档满足数组中任意一个子条件就会被匹配返回- 每个子条件内同时定义
userId和userName,要求两个字段同时匹配才满足该子条件
内容的提问来源于stack exchange,提问作者Gregory Kafanov
相关产品推荐
相关产品推荐

