什么时候在 mongodb 中使用“$and”运算符?
When to use "$and" operator in mongodb?
我在 mongodb 中有一个查询,我必须在其中过滤 印度 中经度在 75 到 80 之间的所有城市,我有这个工作表达式
{"$match":{"country":"India","lon":{"$gt":75},"lon":{"$lt":80}}},
这个表达式工作正常,但是在查看 $and 的文档时,我注意到
Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.
所以根据文档,它应该不能正常工作,因为我多次出现 lon 字段,但它按预期工作。那么任何人都可以向我解释一下场景文档指的是哪里需要 $and 吗?
您关于查询 "working fine" 的结论是不正确的。这些 lon
字段中只有一个会被查询实际使用;可能是第二个。因此查询将 执行 正常,但文档不会被正确过滤。
在 python 提示符处证明:
>>> q = {"$match":{"country":"India","lon":{"$gt":75},"lon":{"$lt":80}}}
>>> q
{'$match': {'country': 'India', 'lon': {'$lt': 80}}}
要遵循的规则是,当您有多个条件用于同一个键时,您应该只使用 $and
,并且不能将它们组合成一个对象。
正如 chidham 指出的那样,您的查询应该构建为将两个 lon
条件组合为:
{"$match": {"country": "India", "lon": {"$gt": 75, "$lt": 80}}}
我在 mongodb 中有一个查询,我必须在其中过滤 印度 中经度在 75 到 80 之间的所有城市,我有这个工作表达式
{"$match":{"country":"India","lon":{"$gt":75},"lon":{"$lt":80}}},
这个表达式工作正常,但是在查看 $and 的文档时,我注意到
Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.
所以根据文档,它应该不能正常工作,因为我多次出现 lon 字段,但它按预期工作。那么任何人都可以向我解释一下场景文档指的是哪里需要 $and 吗?
您关于查询 "working fine" 的结论是不正确的。这些 lon
字段中只有一个会被查询实际使用;可能是第二个。因此查询将 执行 正常,但文档不会被正确过滤。
在 python 提示符处证明:
>>> q = {"$match":{"country":"India","lon":{"$gt":75},"lon":{"$lt":80}}}
>>> q
{'$match': {'country': 'India', 'lon': {'$lt': 80}}}
要遵循的规则是,当您有多个条件用于同一个键时,您应该只使用 $and
,并且不能将它们组合成一个对象。
正如 chidham 指出的那样,您的查询应该构建为将两个 lon
条件组合为:
{"$match": {"country": "India", "lon": {"$gt": 75, "$lt": 80}}}