Pull only one item in an array of instance in MongoDB?

I respect answer by @Prasad_Saya, I am just adding the another option Starting from MongoDB v4.4,

You can use update with aggregation pipeline, and use the $function operator to define custom functions to implement behavior not supported by the MongoDB Query Language.

User.findByIdAndUpdate("5fa4386f3a93dc470c920d76",
[
    {
        $set: {
            characters: {
                $function: {
                    body: function(characters) {
                        for (var i=0; i<characters.length; i++) {
                            if (characters[i] == "5fa4389e3a88888888888888") {
                                delete characters[i];
                                break;
                            }
                        }
                        return characters;
                    },
                    args: ["$characters"],
                    lang: "js"
                }
            }
        }
    }
])
1 Like