Home > Net >  I have to check the condition if both condition are true then its 1 else 0 in MongoDB
I have to check the condition if both condition are true then its 1 else 0 in MongoDB

Time:09-24

I have to check if the value are less equal 100 and "fl1":1 then "fl2": 1 else :0. please check the expected output.

{
    "data": [
        {
            "value": 100,
             "fl" :1
        },
        {
            "value": 300,
             "fl" :0
        },
        {
            "value": 14,
             "fl" :0
        },
        {
            "value": 3
             "fl" :0
        },
        {
            "value": 30,
             "fl" :1
        },
        {
            "value": 60,
             "fl" :1
        }
    ]
}

Expected Output :

{
    "data": [
        {
            "value": 100,
             "fl" :1,
             "fl2":1
        },
        {
            "value": 300,
             "fl" :0,
             "fl2":0
        },
        {
            "value": 14,
             "fl" :0,
             "fl2":0
        },
        {
            "value": 3
             "fl" :0,
             "fl2":0
        },
        {
            "value": 30,
             "fl" :1,
             "fl2":1
        },
        {
            "value": 60,
             "fl" :1,
             "fl2":1
        }
    ]
}

CodePudding user response:

Query

  • map on data
  • if value<100 AND fl=1 => use merge to addfield fl2:1
  • else use merge to addfield fl2:0

Test code here

db.collection.aggregate([
  {
    "$set": {
      "data": {
        "$map": {
          "input": "$data",
          "in": {
            "$cond": [
              {
                "$and": [
                  {
                    "$lte": [
                      "$$m.value",
                      100
                    ]
                  },
                  {
                    "$eq": [
                      "$$m.fl",
                      1
                    ]
                  }
                ]
              },
              {
                "$mergeObjects": [
                  "$$m",
                  {
                    "fl2": 1
                  }
                ]
              },
              {
                "$mergeObjects": [
                  "$$m",
                  {
                    "fl2": 0
                  }
                ]
              }
            ]
          },
          "as": "m"
        }
      }
    }
  }
])
  • Related