1

I have a collection with documents like below:

{
   title: "whatever",
   answers: [
      {id: 10, question: ObjectId("54380350a52147000aad4e9b")},
      {id: 13, question: ObjectId("54380350a52147000aad4e9c")},
      {id: 33}
   ]
}

I'm have attempted to unset the question attribute using the commands below:

db.participants.update({}, {$unset: {"answers.question": ""}}, {upsert: false, multi:true} )

and

db.participants.update({}, {$unset: {"answers.question": 1}}, {upsert: false, multi:true} )

Both of these spit out: WriteResult({ "nMatched" : 628795, "nUpserted" : 0, "nModified" : 0 }) when completed, but no documents are updated (as the message suggests). Any idea why my update isn't working?

1 Answer 1

2

Your update is not working because answers is an array. So you should use the positional operator:

db.participants.update({ 'answers.question': { $exists: true } }, { $unset: { 'answers.$.question': '' } }, { upsert: false, multi: true });

However it updates only one item in the array. This is a limitation of MongoDB, see SERVER-1243.

You can use a forEach to iterate through the items of the array:

db.eval(function () {

    db.participants.find({ 'answers.question': { $exists: true } }).forEach(function (participant) {

        participant.answers.forEach(function (answer) {

            delete answer.question;
        });

        db.participants.update({ _id: participant._id }, { $set: { answers: participant.answers } });
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

+1, thanks for explaining why it wasn't working. Ended up using a modified version of your first update that matched on a condition that would return each array element and then used the positional operator. Seemed a bit simpler than the forEach solution.
Your query with the positional operator still updates only one item in the array. The condition doesn't affect the update in that case.
Oh you're right. Bummer, that seems pretty complex to clear out a value.

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.