简体   繁体   中英

MongoDB Query: Update or push an object in array of object

Let's say I have the following object in regions collection:

{
    "_id": "5e873652b8e8132380343984",
    "region": "Europe",
    "countries": [
        {
            "id": 1,
            "name": "Italy"
        },
        {
            "id": 2,
            "name": "Spain"
        }
    ]
}

Now I want to update a specific country in the countries array based on the id, if the id does not exist, I want to push a new country.

I have the following query which works fine and update a specific country:

Region.findOneAndUpdate(
    { _id: someId, "countries.id": country.id },
    { $set: { [".countries.$"]: country } },
    { new: true }
);

But if the country does not exist in countries object, it doesn't push the country.

in option field you may should try this:

{ new: true, upsert: true}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM