MongoDB中组合多$and与$or及$regex查询的问题求助
MongoDB 查询语句修正方案
错误查询示例
你之前的错误写法大概率是以下两种情况之一:
情况1:同对象重复键被覆盖
db.collection.find({ $or: [ { "preferredTitle.hasValue.value": {$regex: "journal", $options: "i"}, "preferredTitle.hasValue.value": {$regex: "physics", $options: "i"}, "preferredTitle.hasValue.value": {$regex: "Nuclear", $options: "i"}, "abbreviatedTitle.hasValue.value": {$regex: "journal", $options: "i"} } ] })
情况2:$or逻辑拆分错误
db.collection.find({ $or: [ {"preferredTitle.hasValue.value": {$regex: "journal", $options: "i"}}, {"preferredTitle.hasValue.value": {$regex: "physics", $options: "i"}}, {"abbreviatedTitle.hasValue.value": {$regex: "Nuclear", $options: "i"}} ] })
修正后的查询语句
必须用$or包裹两个独立的$and条件组,每个组对应一个字段的多关键词匹配,避免重复键覆盖问题:
db.collection.find({ $or: [ // 第一组:preferredTitle同时匹配三个关键词 { $and: [ {"preferredTitle.hasValue.value": {$regex: "journal", $options: "i"}}, {"preferredTitle.hasValue.value": {$regex: "physics", $options: "i"}}, {"preferredTitle.hasValue.value": {$regex: "Nuclear", $options: "i"}} ] }, // 第二组:abbreviatedTitle同时匹配三个关键词 { $and: [ {"abbreviatedTitle.hasValue.value": {$regex: "journal", $options: "i"}}, {"abbreviatedTitle.hasValue.value": {$regex: "physics", $options: "i"}}, {"abbreviatedTitle.hasValue.value": {$regex: "Nuclear", $options: "i"}} ] } ] })
关键说明
- 避免重复键覆盖:MongoDB不允许同一查询对象里存在重复键,重复的话只会保留最后一个,因此必须用
$and数组包裹同一字段的多个正则条件,确保三个关键词的匹配逻辑都生效。 - $or的正确用法:
$or的每个元素是一个完整的条件集合,只有当集合内所有条件都满足时,才算匹配该分支。这样就实现了“要么preferredTitle同时匹配三个词,要么abbreviatedTitle同时匹配三个词”的需求。
对应文档结构示例
假设你的文档结构如下:
{ "_id": ObjectId("60d21b4667d0d8992e610c85"), "preferredTitle": { "hasValue": { "value": "Nuclear Physics Journal of Research" } }, "abbreviatedTitle": { "hasValue": { "value": "Nucl Phys J" } } }
内容的提问来源于stack exchange,提问作者Arun
相关产品推荐
相关产品推荐

