如何在 pymongo 中进行条件搜索? [英] how can I do a conditional search in pymongo?
问题描述
我正在尝试进行条件查询.我想在整个集合中搜索那些符合 25% 价格范围的文档,并且如果文档有特定字段(在本例中为audiPrice"),我将使用此字段进行搜索,如果该文档具有'不是字段,我将使用'价格'字段
I am trying to make a conditional query. I want to search in the whole collection those documents that fit in range of prices of 25% and if the documents has a particular field(in this case 'audiPrice') I will use this field to do my search, and if this document hasn't the field, I will use a 'price' field
我在 mongodb 文档(https://docs.mongodb.com/manual/reference/operator/aggregation/cond/) 并找到操作符 $cond
并且我尝试进行查询,如您所见
I have search in the mongodb documentation(https://docs.mongodb.com/manual/reference/operator/aggregation/cond/) and found the operator $cond
and I have try to make a the query as you can see
pipeline = [
{
'$cond': {
'if': {'audiPrice': {'$exists': True}}, 'then': {'$match':
{'audiPrice': {
'$lte': price * 1.75, '$gte': price * 0.25
}
}
},'else': {'$match': {
'price': {
'$lte': price * 1.75, '$gte': price * 0.25
}
}
}
}
}
]
我收到了这个错误信息
pymongo.errors.OperationFailure: Unrecognized pipeline stage name: '$cond'
你知道我怎样才能实现我的目标吗?
Do you know how could I achieve my goal?
我正在使用 python 和 pymongo.
I am using python and pymongo.
谢谢
推荐答案
你可以在 $project 中使用 cond 或在 $match 阶段使用 $expr 作为:
You can use cond in $project or $expr in $match stage as:
collectionName.aggregate([
{
$match: {
$expr: {
$cond: {
if: {
$gt: [
"$audiPrice",
null
]
},
then: {
$and: [
{
$gte: [
"$audiPrice",
price * 0.25
]
},
{
$lte: [
"$audiPrice",
price * 1.75
]
}
]
},
else: {
$and: [
{
$gte: [
"$price",
price * 0.25
]
},
{
$lte: [
"$price",
price * 1.75
]
}
]
}
}
}
}
}
])
在这里,您首先检查字段 audiPrice 是否不为空,然后对该键执行匹配,否则对价格键执行匹配.
Here you first check if field audiPrice is not null then perform the match on that key else on price key.
这篇关于如何在 pymongo 中进行条件搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!