4

I have a MongoDB document like this :

{
    "_id": ObjectId("5589044a7019e802d3e9dbc5"),
    "sessionId": LUUID("f49d4280-ced0-9246-a3c9-a63e68e1ed45"),
    "teamId": LUUID("6ef7d1a8-f842-a54c-bd8c-daf6481f9cfc"),
    "variableId": LUUID("59d1b512-eee2-6c4b-a5b5-dda546872f55"),
    "values": {
        "725400": 691.0000000000000000,
        "725760": 686.0000000000000000,
        "726120": 683.0000000000000000,
        "726480": 681.0000000000000000,
        "726840": 679.0000000000000000,
        "727200": 678.0000000000000000,
        "727560": 677.0000000000000000,
        "727920": 676.0000000000000000
    },
    "variableType": 2,
    "isSet": false,
    "teamNumber": 2,
    "simPageIds": []
}

I have a scenario that I have to delete a particular property from the "values" property of my document. for example, I want to delete value "727920" from the "values" property.

Since "Values" is not an array, I can't use $pull here. What I need is to remove

"727920" : 676.0000000000000000 from "values".

What is the right way to do that?

Samuel
  • 263
  • 3
  • 6
  • 17

2 Answers2

23

Use $unset as below :

db.collectionName.update({},{"$unset":{"values.727920":""}})

EDIT For updating multiple documents use update options like :

db.collectionName.update({},{"$unset":{"values.727920":""}},{"multi":true})
Neo-coder
  • 7,715
  • 4
  • 33
  • 52
  • 1
    It works @yogesh. Thanks. But I totally have more than 50 documents in my collection like this. But when I execute the above query, the first document only gets updated. What must I do to update all my document in my collection? – Samuel Jul 13 '15 at 13:27
5

You may try the following query using $unset

For single document update,

db.collectionName.update({ /* filter condition */ }, { $unset : { "ParentKey.ChildKey" : 1} })

For multiple documents update,

db.collectionName.updateMany({ /* filter condition */ }, { $unset : { "ParentKey.ChildKey" : 1} })
20B2
  • 2,011
  • 17
  • 30