匹配少于 MongoDB 的所有字段

matching fewer than all fields with MongoDB

假设我有一个 MongoDB 查询,如下所示:

result = db.collection.find(
    {
        'fruit_type': 'apple', 
        'fruit_name': 'macintosh' 
        'primary_color': 'red', 
        'sheen': 'glossy', 
        'origin_label': 'true', 
        'stem_present': 'true', 
        'stem_leaves_present': 'true', 
        'blemish': 'none', 
        'firmness': 'moderate'
    }
)

当我有完全匹配时,我只想要完全匹配。当我没有完全匹配时,然后(并且只有那时)我想要其他苹果,唯一的必填字段和值是 'fruit_type': 'apple''primary_color': 'red'.

注意:为清楚起见,此问题已被多次编辑

确保您至少满足强制性条件的最接近方法是将所有可选查询字段与 $or 运算符中的一个强制性字段放在一起,因为它 select s 满足 $or 运算符表达式中至少一个可选表达式的文档:

result = db.collection.find(
    {
        'fruit_type': 'apple',                       
        "$or": [ 
            { 'primary_color': 'red' },
            { 'fruit_name': 'macintosh' }, 
            { 'sheen': 'glossy' }, 
            { 'origin_label': 'true' }, 
            { 'stem_present': 'true' }, 
            { 'stem_leaves_present': 'true' }, 
            { 'blemish': 'none' }, 
            { 'firmness': 'moderate' }
        ]
    }
)

上述查询将 select 集合中 fruit_type 字段值为 apple 且 primary_color 字段值为 red 的所有文档。如果在您的集合中没有 primary_color 字段值为红色的文档,那么上面将不会 return 任何文档。

在性能方面,如果这两个必填字段是经常发出的查询,请考虑在它们上创建复合索引,因为扫描索引比扫描集合快得多。

有关详细信息,请阅读 Optimize Query Performance and Behaviors - $or Clauses and Indexes

上的文档部分