1

I'm working with MongoDB (by using Mongoose on NodeJS).

{
"_id":{"$oid":"5fa4386f3a93dc470c920d76"},
"characters":[
    {"$oid":"5fa4389e3a93dc470c920d78"},
    {"$oid":"5fa4389e3a88888888888888"},
    {"$oid":"5fa4389e3a88888888888888"},
    {"$oid":"5fa4389e3a88888888888888"}
    ]
}

I tried to remove only one row of object id "5fa4389e3a88888888888888" in my characters array. By doing..

User.findByIdAndUpdate("5fa4386f3a93dc470c920d76", { $pull: { characters: "5fa4389e3a88888888888888" } }, (err) => {});

The problem is that every row with "5fa4389e3a88888888888888" value are removed. And I'd just like to pull 1.

Is it possible ?

Thanks for helping

1 Answer 1

1

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. Starting from MongoDB v4.4,

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"
                }
            }
        }
    }
])
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.