Danyal
Danyal

Reputation: 56

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 column always results to true, WHY?

only one row should show status column true for { __type: "TaskPlannedResource" }

Upvotes: 1

Views: 1144

Answers (1)

turivishal
turivishal

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
        ]
      }
    }
  }

Playground


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"] }
        ]
      }
    }
  }

Playground


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"
            ]
          }
        ]
      }
    }
  }
]));

Playground

Upvotes: 2

Related Questions