Reputation: 56
[{ "_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
column always results to true, WHY?
only one row should show status
column true for
{ __type: "TaskPlannedResource" }
Upvotes: 1
Views: 1144
Reputation: 36114
You need to correct the syntax of equal to $eq
in condition $cond
operation, you have used query condition but this requires expression $eq
condition operator,
{
$project: {
status: {
$cond: [
{
$or: [
{ $eq: ["$__type", "TaskPlannedResource"] },
{ $eq: ["$boqType", "1"] }
]
},
true,
false
]
}
}
}
The second option as well, the $or
or any expression operator condition will return true/false, so no need to use $cond
operator,
{
$project: {
status: {
$or: [
{ $eq: ["$__type", "TaskPlannedResource"] },
{ $eq: ["$boqType", "1"] }
]
}
}
}
The third option is to merge both $project
stages in single, you can put $ifNull
condition inside $eq
instead of direct field name,
let result = (await sampleModel.aggregate([
{
$project: {
status: {
$or: [
{
$eq: [
{ $ifNull: ["$__type", "0"] },
"TaskPlannedResource"
]
},
{
$eq: [
{ $ifNull: ["$boqType", "0"] },
"1"
]
}
]
}
}
}
]));
Upvotes: 2