Reputation: 276
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
Upvotes: 1
Views: 259
Reputation: 36134
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"
}
}
}
}
])
Upvotes: 1