1

How to unset field(array) if its length after $pull operation equals 0 in MongoDB?

I need to do it using only 1 query. Is it possible?

1 Answer 1

1

There is no way in a regular update query, but You can try update with aggregation pipeline starting from MongoDB 4.2,

Consider this is a sample document and you want to pull "1" from array field:

{
  "array": [1]
}
  • $filter to iterate loop of array and filter array that is not equal to "1"
  • $cond to check after pull, is array field empty then remove by $$REMOVE otherwise nothing to do
db.collection.update(
  { "array": 1 },
  [{
    $set: {
      array: {
        $filter: {
          input: "$array",
          cond: { $ne: ["$$this", 1] }
        }
      }
    }
  },
  {
    $set: {
      array: {
        $cond: [
          { $eq: ["$array", []] },
          "$$REMOVE",
          "$array"
        ]
      }
    }
  }]
)

Playground


The second alternate option,

  • $cond to check is array equal to the single element that we are going to pull [1] then remove array field otherwise go to $filter operation to remove single element
db.collection.update(
  { "array": 1 },
  [{
    $set: {
      array: {
        $cond: [
          { $eq: ["$array", [1]] },
          "$$REMOVE",
          {
            $filter: {
              input: "$array",
              cond: { $ne: ["$$this",1] }
            }
          }
        ]
      }
    }
  }]
)

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.