Mongo聚合查询布尔条件总是returnstrue
Mongo aggregate query Boolean condition always returns true
[{ "_id" : ObjectId("610d10db038380dde8f33bcc"),
"__type" : "TaskPlannedBOQ",
"boqType" : "4",
},
{
"_id" : ObjectId("610d10db038380dde8f33bc9"),
"__type" : "TaskPlannedResource",
}]
let result = (await sampleModel.aggregate([
{ $project: { boqType: { $ifNull:["$boqType", "0"]},__type: { $ifNull:["$__type", "0"]}}},
{ $project: { status: {$cond: [{$or: [{ __type: "TaskPlannedResource" },{ boqType: "1" }]},true,false]}}}]))
status
列的结果始终为真,为什么?
只有一行应该显示 status
列 true
{ __type: "TaskPlannedResource" }
您需要更正条件$cond
操作中等于$eq
的语法,您使用了查询条件但这需要表达式$eq
条件运算符,
{
$project: {
status: {
$cond: [
{
$or: [
{ $eq: ["$__type", "TaskPlannedResource"] },
{ $eq: ["$boqType", "1"] }
]
},
true,
false
]
}
}
}
第二个选项也是如此,$or
或任何表达式运算符条件将 return true/false,因此无需使用 $cond
运算符,
{
$project: {
status: {
$or: [
{ $eq: ["$__type", "TaskPlannedResource"] },
{ $eq: ["$boqType", "1"] }
]
}
}
}
第三个选项是将两个 $project
阶段合并为一个,您可以将 $ifNull
条件放在 $eq
中而不是直接字段名称,
let result = (await sampleModel.aggregate([
{
$project: {
status: {
$or: [
{
$eq: [
{ $ifNull: ["$__type", "0"] },
"TaskPlannedResource"
]
},
{
$eq: [
{ $ifNull: ["$boqType", "0"] },
"1"
]
}
]
}
}
}
]));
[{ "_id" : ObjectId("610d10db038380dde8f33bcc"),
"__type" : "TaskPlannedBOQ",
"boqType" : "4",
},
{
"_id" : ObjectId("610d10db038380dde8f33bc9"),
"__type" : "TaskPlannedResource",
}]
let result = (await sampleModel.aggregate([
{ $project: { boqType: { $ifNull:["$boqType", "0"]},__type: { $ifNull:["$__type", "0"]}}},
{ $project: { status: {$cond: [{$or: [{ __type: "TaskPlannedResource" },{ boqType: "1" }]},true,false]}}}]))
status
列的结果始终为真,为什么?
只有一行应该显示 status
列 true
{ __type: "TaskPlannedResource" }
您需要更正条件$cond
操作中等于$eq
的语法,您使用了查询条件但这需要表达式$eq
条件运算符,
{
$project: {
status: {
$cond: [
{
$or: [
{ $eq: ["$__type", "TaskPlannedResource"] },
{ $eq: ["$boqType", "1"] }
]
},
true,
false
]
}
}
}
第二个选项也是如此,$or
或任何表达式运算符条件将 return true/false,因此无需使用 $cond
运算符,
{
$project: {
status: {
$or: [
{ $eq: ["$__type", "TaskPlannedResource"] },
{ $eq: ["$boqType", "1"] }
]
}
}
}
第三个选项是将两个 $project
阶段合并为一个,您可以将 $ifNull
条件放在 $eq
中而不是直接字段名称,
let result = (await sampleModel.aggregate([
{
$project: {
status: {
$or: [
{
$eq: [
{ $ifNull: ["$__type", "0"] },
"TaskPlannedResource"
]
},
{
$eq: [
{ $ifNull: ["$boqType", "0"] },
"1"
]
}
]
}
}
}
]));