我在MongoDB中遇到了以下问题:
在sample_training.companies数据集中有多少家公司
创建于10月份&(拥有社交category_code或web category_code)
对上述问题的实际查询如下,并返回149份文件。
CorrectQuery:
db.companies.find({
"$or":[
{
"founded_year":2004,
"$or":[
{ "category_code":"social" },
{ "category_code":"web" }
]
},
{
"founded_month":10,
"$or":[
{ "category_code":"social" },
{ "category_code":"web" }
]
}
]
}).count()但是,我尝试为同样的问题编写另一个查询,不幸的是,它返回了668行的不正确值。
不正确的查询:
db.companies.find({
"$or":[
{"category_code":"social"},
{"category_code":"web"}
],
"$or":[
{"founded_year":2004},
{"founded_month":10}
]
}).count()有人能帮助我理解这些查询之间的区别吗?
发布于 2022-02-10 09:25:49
答案只是布尔逻辑中操作的标准顺序。
AND比OR有优先权,就像乘法在数学上比加法有优先权一样。
第一个例子是正确的,因为逻辑与问题中的逻辑匹配。
第二个例子逻辑是:
(category_code is "social" or category_code is "web") and (founded_year is 2004 or founded_month is 10)你的第二个例子:
db.companies.find({
"$or":[
{"category_code":"social"},
{"category_code":"web"}
],
"$or":[
{"founded_year":2004},
{"founded_month":10}
]
}).count()https://stackoverflow.com/questions/71000558
复制相似问题