Search code examples
arraysmongodbmongodb-querynosql

In mongoDb, how do you remove a array element on specific index position?


In the following example, assume the document is in the db.people collection.

I want to remove an element of index 3 from item list. How can I remove the specific element at index 3?

{
    "_id": "6527c64e539e51befb0db39c",
    "category": "fruits",
    "dataType": "string",
    "isList": true,
    "item": [
        null,
        "mango",
        "banana",
        "kiwi",
        "orange",
        null,
        "watermelon"
    ]
}

This is what I tried:

db.people.update({_id:ObjectId('6527c64e539e51befb0db39c')}, {$unset : {"item.3" : 1 }}) 
db.people.update({_id:ObjectId('6527c64e539e51befb0db39c')}, {$pull : {"item" : null}})

Result I got: It removed all the null values from the item array field.

{
    "_id": "6527c64e539e51befb0db39c",
    "category": "fruits",
    "dataType": "string",
    "isList": true,
    "item": [
        "mango",
        "banana",
        "kiwi",
        "orange",
        "watermelon"
    ]
}

What result I want:

{
    "_id": "6527c64e539e51befb0db39c",
    "category": "fruits",
    "dataType": "string",
    "isList": true,
    "item": [
        null,
        "mango",
        "banana",
        "orange",
        null,
        "watermelon"
    ]
}

Solution

  • Use $slice to get first and later halves of the array before and after the element. Then return it with $concatArrays and $set for the update.

    db.collection.update({
      _id: ObjectId("6527c64e539e51befb0db39c")
    },
    [
      {
        "$set": {
          "item": {
            "$concatArrays": [
              {
                "$slice": [
                  "$item",
                  3
                ]
              },
              {
                "$slice": [
                  "$item",
                  4,
                  {
                    "$size": "$item"
                  }
                ]
              }
            ]
          }
        }
      }
    ])
    

    Mongo Playground