You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB深度嵌套查询无数据返回的逻辑原因咨询

为什么MongoDB的Query4返回0条文档?

我为MongoDB设计了嵌套查询结构,Query1、Query2、Query3都能正常获取数据,但Query4返回0条文档。我已经用Query3实现了需求,现在只需要理解Query4查询失败的逻辑原因。


可正常返回数据的查询

Query1

{
    $and : [
        {
            $or : [
                {
                    $and : [
                        {name : /google/i},
                        {date : {$gte : new Date("2002-07-01T00:00:00.000Z")}},
                        {date : {$lt : new Date("2002-07-05T00:00:00.000Z")}}
                    ]
                }
            ]
        }
    ]
}

Query2

{
    $and : [
        {
            $or : [
                {
                    $and : [
                        {name : /microsoft/i},
                        {date : {$gte : new Date("2002-07-08T00:00:00.000Z")}},
                        {date : {$lt : new Date("2002-07-12T00:00:00.000Z")}}
                    ]
                }
            ]
        }
    ]
}

Query3

{
    $and : [
        {
            $or : [
                {
                    $and : [
                        {name : /google/i},
                        {date : {$gte : new Date("2002-07-01T00:00:00.000Z")}},
                        {date : {$lt : new Date("2002-07-05T00:00:00.000Z")}}
                    ]
                },
                
                {
                    $and : [
                        {name : /microsoft/i},
                        {date : {$gte : new Date("2002-07-08T00:00:00.000Z")}},
                        {date : {$lt : new Date("2002-07-12T00:00:00.000Z")}}
                    ]
                }
            ]
        }
    ]
}

返回0条文档的Query4

{
    $and : [
        {
            $or : [
                {
                    $and : [
                        {name : /google/i},
                        {date : {$gte : new Date("2002-07-01T00:00:00.000Z")}},
                        {date : {$lt : new Date("2002-07-05T00:00:00.000Z")}}
                    ]
                }
            ]
        }, {
            $or : [
                {
                    $and : [
                        {name : /microsoft/i},
                        {date : {$gte : new Date("2002-07-08T00:00:00.000Z")}},
                        {date : {$lt : new Date("2002-07-12T00:00:00.000Z")}}
                    ]
                }
            ]
        }
    ]
}

逻辑原因分析

Query4的核心结构是顶级$and包含两个独立的条件组,这要求同一条文档必须同时满足以下两个完全互斥的条件:

  1. 文档的name匹配/google/i,且date落在2002-07-01至2002-07-05之间;
  2. 该文档的name同时匹配/microsoft/i,且date落在2002-07-08至2002-07-12之间。

显然,一条文档的name不可能同时是google和microsoft,date也不可能同时处于两个不重叠的时间段内,因此没有任何文档能满足这个逻辑要求,最终返回0条结果。

而Query3的结构是顶级$and内部包含一个$or,$or下有两个互斥的条件组,只要求文档满足其中任意一个条件组即可,因此能正常匹配到符合google或microsoft条件的文档。


内容的提问来源于stack exchange,提问作者Himanshu Agrawal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:21:31