7

How can I unset an attribute from a single array element from the Mongo console. For example, how do I unset the junk attribute from time[1]

{
  "_id" : ObjectId("4d525ab2924f0000000022ad"), 
  "name" : "hello", 
  "time" : [
      {
          "stamp" : "2010-07-01T12:01:03.75+02:00",
          "reason" : "new"
      },
      {
          "stamp" : "2010-07-02T16:03:48.187+03:00",
          "reason" : "update",
          "junk"  : "yes"
      },
      {
          "stamp" : "2010-07-02T16:03:48.187+04:00",
          "reason" : "update"
      },

   ]
}
rdsoze
  • 1,768
  • 1
  • 15
  • 25

1 Answers1

12

This should do the trick:

db.coll.update({"time.junk": "yes"}, {$unset: {"time.$.junk": 1}});

Read on dot notation.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • Actually it will remove the value, BUT only from the first occurrence of the subdocument, because "the positional $ operator acts as a placeholder for the first element that matches the query document" (https://docs.mongodb.org/manual/reference/operator/update/positional/#query) Also: see Hassek's hack here: http://stackoverflow.com/questions/19945924/remove-a-field-from-array-element-in-mongodb – Patrycja K Feb 02 '16 at 16:45