S
S
Stanislav2017-07-29 23:23:34
MongoDB
Stanislav, 2017-07-29 23:23:34

How to update a field in an array of objects in MongoDB?

When using the $in operator on an array of objects, for some reason it only updates the first object.
Document structure:

{
    _id: 'ID document',
    comments: [{
        _id: ObjectId("597cea075b116f0e9e2cca55"),
        closed: false,
        text: "string"
    }, {
        _id: ObjectId("597ce96f5b116f0e9e2cca54"),
        closed: false,
        text: "string"
    }]
}

I pass an array of identifiers to the request ['597cea075b116f0e9e2cca55', '597ce96f5b116f0e9e2cca54']
Here is the request itself
Posts
    .update({
        'comments._id': {
            $in: commentsIds
        }
    },{
        $set: {
            'comments.$.closed': true
        }    
    }, (e) => {
        console.log(e);
        process.exit();
});

With such a request, the first ID from the array is taken and the comments.closed field is changed, other IDs are not affected for some reason. There are no errors. How to be? Change everything in a cycle?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question