如何在管道聚合(mongoDB)中比较文档中的两个字段 [英] how to compare two fields in a document in pipeline aggregation (mongoDB)
问题描述
我有一个如下文件:
{
"user_id": NumberLong(1),
"updated_at": ISODate("2016-11-17T09:35:56.200Z"),
"created_at": ISODate("2016-11-17T09:35:07.981Z"),
"banners": {
"normal_x970h90": "/images/banners/4/582d79cb3aef567d64621be9/photo-1440700265116-fe3f91810d72.jpg",
"normal_x468h60": "/images/banners/4/582d79cb3aef567d64621be9/photo-1433354359170-23a4ae7338c6.jpg",
"normal_x120h600": "/images/banners/4/582d79cb3aef567d64621be9/photo-1452570053594-1b985d6ea890.jpg"
},
"name": "jghjghjghj",
"budget": "2000",
"plan": null,
"daily_budget": "232323",
"daily_budget_auto": "",
"href": "qls2.ir",
"targets": {
"cats": [
"fun",
"news"
],
"region": "inIran",
"iran_states": null,
"os": "all",
"gold_network": true,
"dont_show_between_1_n_8": true
},
"payment": {
"bank": "mellat",
"tax": "add"
},
"click_cost": "102000",
"status": null
}
在检查查询中的其他一些参数时,我想检查budget
是否低于click_cost
:
I want to check if budget
is lower than click_cost
while I'm checking some other parameters in my query :
db.bcamp.aggregate(
[
{
$match:{
$and: [
{"targets.cats":{
"$in" : ["all"]
}
},
{"banners.normal_x970h90":{
"$exists":true
}
},
{"href": {
$nin: ["qls.ir"]
}
}
]
}
}
]).pretty();
我尝试过比较方法:
db.bcamp.aggregate(
[
{$project: {ab: {$cmp: ['$budget','$clickcost']}}},
{$match: {ab:{$gt:1}}}
]).pretty();
但是我得到的结果是错误的,它总是返回4个文档,它们的预算可能比click_cost更好,这意味着它获取了错误的数据.
But I was getting wrong result, it returns always 4 document which their budget may or may not be grater than click_cost, which it means it fetch wrong data.
如何将该比较添加到我的mongoDB管道中?
How can I add that comparison to my mongoDB pipeline?
推荐答案
问题不在于比较运算符,它是您要比较的值的类型.您应该将变量的类型更改为Numbers.根据您的比较将匹配项更改为1,-1或0.
The problem is not with comparison operator, its the type of value you are comparing. You should change types of variable to Numbers. Change your match to 1, -1 or 0 based on your comparison.
db.bcamp.aggregate(
[
{$project: {ab: {$cmp: ['$budget','$clickcost']}}},
{$match: {ab:{$eq:1}}}
]).pretty();
您可以在3.6版本中使用$expr
.
You can use $expr
in 3.6 version.
db.bcamp.aggregate(
[
{$match: {$expr: {$eq: ["$budget", "$clickcost"]}}}
]).pretty();
或
db.bcamp.find(
{$expr: {$eq: ["$budget", "$clickcost"]}}
).pretty();
这篇关于如何在管道聚合(mongoDB)中比较文档中的两个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!