简体   繁体   中英

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

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

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

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