How to remove an element from array

What’s up! I’m learning MongoDB using the new shell.

My data looks like this:

 {
    _id: ObjectId("623b21fac400655e8a41eab6"),
    name: 'test alertas',
    color: 'blue',
    polygon: {
      type: 'Polygon',
      coordinates: [
        [ -33.22578760424157, -71.05464839658427 ],
        [ -33.21947054548265, -70.38837445413999 ],
        [ -33.503858383102184, -70.39043509519908 ],
        [ -33.50786526545292, -71.07250728576321 ],
        [ -33.23382683744136, -71.09173993564818 ]
      ],
      _id: ObjectId("623b21fac400655e8a41eab7")
    },
    alerts: [
      {
        type: 'Variacion Rumbo',
        active: false,
        params: '',
        _id: ObjectId("623b21fac400655e8a41eab8")
      },
      {
        type: 'Perdida Señal GPS',
        active: true,
        params: '60',
        _id: ObjectId("623b21fac400655e8a41eab9")
      },
      {
        type: 'Zona Peligro',
        active: true,
        params: '',
        _id: ObjectId("623b21fac400655e8a41eaba")
      },
      {
        type: 'Rango Velocidad',
        active: false,
        params: '',
        _id: ObjectId("623b21fac400655e8a41eabb")
      },
      {
        type: 'Variacion Velocidad',
        active: false,
        params: '',
        _id: ObjectId("623b21fac400655e8a41eabc")
      }
    ],
    userId: '620439e2336442814abed152',
    __v: 0
  }

This “zones” collection has objets like this. I’d like to remove all the _id fields from inside the alerts array. What’s the query for that? I tried this: db.zones.updateMany({}, {$unset: {“alerts._id”: 0}})
Didn’t work.

Hi,

You can use $set with $map:

db.collection.update({},
[
  {
    "$set": {
      "alerts": {
        "$map": {
          "input": "$alerts",
          "in": {
            "type": "$$this.type",
            "acrive": "$$this.active",
            "params": "$$this.params"
          }
        }
      }
    }
  }
])

Working example

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.