0

I have the following objects in MongoDB

 {
    "_id": {
        "$oid": "5f7274fe0fef0e383459e3ae"
    },
    "pwd": "$2a$10$AmA3lqNRdt315pgA3z9vNOkFMwisnu5zfcq0qVJzVSVm/0VYy3uQu",
    "daysfree": [{
        "date": {
            "$date": "2020-10-12T21:00:00.000Z"
        },
        "friends": ["pota", "toto", "loto"]
    }]
}

{
    "_id": {
        "$oid": "5f7b372d1c70e33c1cc41ec3"
    },
    "pwd": "$2a$10$H.2LGua3T2/wRhik792RtuPHJSzhRSJj5f6eV5bz/iGHywQ7Ylr2y",
    "daysfree": [{
        "date": {
            "$date": "2020-10-12T21:00:00.000Z"
        },
        "friends": ["hi", "hilo", "pota", "toto", "loto", "pota", "toto", "loto"]
    }]
}

And I want to update them such that for each document if the daysfree contains an object with the field date being set to "2020-10-12T21:00:00.00Z" then in the same exact object push to friends a new String.

Here are the queries I have tried that do half the job.

db.collection.update({
    "daysfree":{
        $elemMatch:{
            "date":{
                "$gte":ISODate("2020-10-12T00:00:00Z"),
                "$lt": ISODate("2020-10-13T00:00:00Z")
                }
            }
        }
    },{
        $push:{
            "daysfree.$.friends":"Josef"
        }
    }
);

The problem is that the query only updates the first document and not both of them.

Regards.

1 Answer 1

1

update updates only the first matching document. Either use updateMany (which I prefer) or put optional parameter {multi: true}.

db.collection.update({
    "daysfree":{
        $elemMatch:{
            "date":{
                "$gte":ISODate("2020-10-12T00:00:00Z"),
                "$lt": ISODate("2020-10-13T00:00:00Z")
                }
            }
        }
    },
    { $push:{ "daysfree.$.friends":"Josef" } },
    { multi: true }
);

db.collection.updateMany({
    "daysfree":{
        $elemMatch:{
            "date":{
                "$gte":ISODate("2020-10-12T00:00:00Z"),
                "$lt": ISODate("2020-10-13T00:00:00Z")
                }
            }
        }
    },
    { $push:{ "daysfree.$.friends":"Josef" } },
);
Sign up to request clarification or add additional context in comments.

Comments

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.