0

I'm using MongoDB to store my data. I got a collection whichs documents have this look:

{
  "_id": UUID("61d2a9c4-0d8a-4106-ab50-8d4ada96bfdf"),
  "some": "field",
  "data": {
    "1d19bca7-7edb-4085-a2c3-fa92c6faf3bd": {
      "a": "nested object"
    },
    "7f812369-c4ff-4e90-9f2c-27904bb03e8d": {
      "a": "nother nested object"
    }
  }
}

I would now like to remove data.7f812369-c4ff-4e90-9f2c-27904bb03e8d. I tried it with $unset but you can just set the field to null but not remove it. Another approach I did was using $pull but I thinks it's only assumed to be used for arrays. So how could I remove the data.7f812369-c4ff-4e90-9f2c-27904bb03e8d field?

Any help appreciated


EDIT:

db.getCollection('mycollection').update({
  "_id": UUID("61d2a9c4-0d8a-4106-ab50-8d4ada96bfdf")
}, {
  $unset: {
    "data.1d19bca7-7edb-4085-a2c3-fa92c6faf3bd": null
  }
});

actually works. Can't remember what I did wrong the other when. Thanks alot to everybody helping.

Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38
plazmakeks
  • 161
  • 1
  • 10
  • the `$unset` did remove the key from collection. At least in my server. – Mạnh Quyết Nguyễn May 30 '18 at 14:55
  • 1
    `$unset` is how you do this. Can you update your question to show what you're trying with `$unset`? The `null` setting only occurs within array fields, which doesn't apply here. – JohnnyHK May 30 '18 at 14:56
  • `$unset` will only result to `null` if you are trying to unset any array index. `$unset` is the right way to do this , since you are not working with arrays, – 0.sh May 30 '18 at 15:03

0 Answers0