Question

I have a collection of the form

{ 
   "student_id":"123",
   "test": [ { "date_created": "12/3/2013" } ]
}

I want to unset the date field. I use the following query:

db.student.update({ "student_id" : "1234"} { "$unset" : { "test.$.date_created" : ""}})

I also tried this:

db.student.update({ "student_id" : "1234"} { "$unset" : { "test.date_created" : ""}})

but, it doesn't work.

Was it helpful?

Solution

You should take a look at the docs again about updates with a positional operator.

From the docs:

The array field must appear in the query argument in order to determine which array element to update.

so, we can get what you want to happen by doing the following:

db.student.update({ student_id: 123, 'test.date_created': { $exists: true } }, { $unset: { 'test.$.date_created': "" } }

That will unset the field off the first object in the array that has a date_created.

If you know the position of the date_created field in the array you want to remove:

db.student.update({ student_id: 123 }, { $unset: { 'test.0.date_created': "" } }

If you know the date you want to remove:

db.student.update({ student_id: 123, 'test.date_created': "12/3/2013" }, { $unset: { 'test.$.date_created': "" } }

However, because of the schema in your example, that will leave you with an empty object inside your array...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top