skip to Main Content
{
    "offers" : [
        {
            "name" : "min",
            "prices" : [
               8, 15, 18
            ]
        },
        {
            "name" : "max",
            "prices" : [
               9, 11, 18
            ]
        }
    ],
    "nl" : [
        2, 4, 6, 7
    ]
}

update aggregation not working $in. I have tried on the two ways

[
    {
      $set: {
          offers: {
              $cond: {
                  if: {
                        "nl": {$in: [7]}
                  },
                   then: {
                          $concatArrays: ["$offers", []]
                      },
                  else: {
                        $concatArrays: ["$offers", [{
                                "name" : "minimal",
                                "prices" : []
                            }]]
                      }
              }
          }
      }
    },
   ]

The code below is not working and not showing any error.

[
    {
      $set: {
          offers: {
              $cond: {
                  if: {
                        $in: ["$nl", 7]
                  },
                   then: {
                          $concatArrays: ["$offers", []]
                      },
                  else: {
                        $concatArrays: ["$offers", [{
                                "name" : "minimal",
                                "prices" : []
                            }]]
                      }
              }
          }
      }
    },
   ]

I want to cancat with offers array according to the exi/stence of 7 in the field "nl". Please help me. I am trying to solve this problem during 5 hours.

2

Answers


  1. $in on aggregation is on this syntax: (see MongoDb Docs)

    { $in: [ <expression>, <array expression> ] }
    

    You need to inverse $in condition. Like this:

    $in: [7, "$nl"]
    
    Login or Signup to reply.
  2. I’m not sure what your expected outcome is but you need to pass the number 7 as the first argument (a valid expression) and the array to compare against as the second (a valid expression that resolves to an array) like so:

    {
        $set: {
          offers: {
            $cond: [
              {
                $in: [
                  7,
                  "$nl"
                ]
              },
              {
                $concatArrays: [
                  "$offers",
                  []
                ]
              },
              {
                $concatArrays: [
                  "$offers",
                  [
                    {
                      "name": "minimal",
                      "prices": []
                    }
                  ]
                ]
              }
            ]
          }
        }
      }
    

    See HERE for a working example.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search