如何在 mongo 文档中过滤对象 ID 的“数组”,使其不包含“60ba4ca6f170dsfa234”,并且将更新文档。谢谢!
{
"_id" : ObjectId("60bfdae011abd61c3eec"),
"array" : [
ObjectId("60ba4ca6f170dsfa234"),
ObjectId("60bd240df30ead9293d")
}
答案 0 :(得分:0)
您可以通过 $project
选项使用 $filter
管道阶段。
db.collection.aggregate([
{
"$project": {
"array": {
"$filter": {
"input": "$array",
"cond": {
"$ne": [
"$$this",
{ // <-- Ignore this block and pass value directly you are passing `ObjectId` directly drom driver and conversion from string is not required
"$toObjectId": "60407d54a8204c86a62bf231" // <-- ObjectId you want to be removed from the array
}
],
},
}
},
},
},
{
"$merge": {
"into": "collection", // <-- Change to source collection name where the changes has to be updated
"on": "_id",
"whenMatched": "merge",
},
},
])