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

Time:11-13

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

CodePudding user response:

you can't do it with mongoDb directly

But you can find the key in python

value = "xxx"
for key in obj["sensor"].keys():
    if obj["sensor"][key] == value:
        # Mongoquery to $unset 'key' 

CodePudding user response:

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" } } }
])
  • Related