Rohit
Rohit

Reputation: 1

How do i remove a item in a object if i did not know the key name in MongoDB?

Please refer this image

Please refer the image, Here i want to delete bearing_accelerometer_sensor field but i dont know this key name but i know the value here (i.e ObjectId("618e3fc8fccb88b50f2d9317")), I'm aware we can use this query db.getCollection('algorithm_association_collection').update({},{"$unset":{"sensor.bearing_accelerometer_sensor":""}}) to delete the field but in my case i dont know the key name "bearing_accelerometer_sensor". Pls help thanks in advance

Upvotes: 0

Views: 35

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59456

You can use this one:

db.collection.aggregate([
  {
    $set: {
      sensor: {
        $filter: {
          input: { $objectToArray: "$sensor" },
          cond: { $ne: [ "$$this.v", ObjectId("618e3fc8fccb88b50f2d9317") ] }
        }
      }
    }
  },
  { $set: { sensor: { $arrayToObject: "$sensor" } } }
])

Mongo Playground

If you like to update existing collection, you can use the pipeline in an update statement:

db.collection.updateMany({}, [
  {
    $set: {
      sensor: {
        $filter: {
          input: { $objectToArray: "$sensor" },
          cond: { $ne: [ "$$this.v", ObjectId("618e3fc8fccb88b50f2d9317") ] }
        }
      }
    }
  },
  { $set: { sensor: { $arrayToObject: "$sensor" } } }
])

Upvotes: 1

Related Questions