gpt4 book ai didi

mongodb - 查询字典字段不存在或存在且为空的 Mongodb 文档

转载 作者:行者123 更新时间:2023-12-04 16:11:03 28 4
gpt4 key购买 nike

假设有一些文档:

# No 'value'
{
'name': 'T1',
}

# 'value' is a non-empty dict
{
'name': 'T1',
'value': {'a':'A', 'b':'B'}
}

# 'value' is a empty dict
{
'name': 'T1',
'value' : {}
}

我想查询的是 value 不存在或 value 存在但为空的文档。我尝试了以下方法但不起作用:

cursor = collection.find({
'name': {"$exists": 1},
'value': {"$or": [{"$exists":0}, {"$eq": {}}]}
})

错误:

pymongo.errors.OperationFailure: unknown operator: $or

最佳答案

根据 $or docs $or 只能用作顶级键,不能用作字段过滤器内部。所以你需要反转你的第二个条件:

collection.find({
"name": { "$exists": 1 },
"$or": [ { "value": { "$exists": 0 } }, { "value": { "$eq": {} } } ]
})

关于mongodb - 查询字典字段不存在或存在且为空的 Mongodb 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41407600/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com