我有一份如下文件:
{
"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
而我在查询中检查了其他一些参数:
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更重要或更糟,这意味着它会获取错误的数据。
如何将该比较添加到我的mongoDB管道?
答案 0 :(得分:16)
问题不在于比较运算符,而是您要比较的值的类型。您应该将变量类型更改为Numbers。根据您的比较将您的匹配更改为1,-1或0。
db.bcamp.aggregate(
[
{$project: {ab: {$cmp: ['$budget','$clickcost']}}},
{$match: {ab:{$eq:1}}}
]).pretty();
您可以在3.6版本中使用$expr
。
db.bcamp.aggregate(
[
{$match: {$expr: {$eq: ["$budget", "$clickcost"]}}}
]).pretty();
或者
db.bcamp.find(
{$expr: {$eq: ["$budget", "$clickcost"]}}
).pretty();