简体   繁体   English

在 MongoDB 的实例数组中仅拉取一项?

[英]Pull only one item in an array of instance in MongoDB?

I'm working with MongoDB (by using Mongoose on NodeJS).我正在使用 MongoDB(通过在 NodeJS 上使用 Mongoose)。

{
"_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.我试图在我的字符数组中只删除一行 object id "5fa4389e3a88888888888888"。 By doing..通过做..

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

The problem is that every row with "5fa4389e3a88888888888888" value are removed.问题是每行具有“5fa4389e3a88888888888888”值的行都被删除了。 And I'd just like to pull 1.我只想拉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.您可以将update 与聚合管道一起使用,并使用$function运算符定义自定义函数以实现 MongoDB 查询语言不支持的行为。 Starting from MongoDB v4.4,从 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"
                }
            }
        }
    }
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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