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"
      },

   ]
}

1 Answer 1

12

This should do the trick:

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

Read on dot notation.

Sign up to request clarification or add additional context in comments.

1 Comment

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" (docs.mongodb.org/manual/reference/operator/update/positional/…) Also: see Hassek's hack here: stackoverflow.com/questions/19945924/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.