MongoDB如何用id和更新值更新对象数组

goqiplq2  于 2022-11-28  发布在  Go
关注(0)|答案(2)|浏览(208)

我有对象数组:

[
 {_id: "5ca2141da0106d1320c0ae32", detail: 1},
 {_id: "5ca2141da0106d1320c0ae33", detail: 3},
 {_id: "5ca2141da0106d1320c0ae34", detail: 3}
]

我如何通过id和数组中的值更新文档?我尝试这样做:

arrayOfObjects.map(i => {
        ids.push(i._id);
        details.push(i.detail);
    });
Model.updateMany(
        { _id: { $in: ids } },
        { $set: { detail: details} },

我是否应该为set运算符获取$in: ids索引?

envsm3lx

envsm3lx1#

这是你的数组。

var arrayofObjects = [
  {_id: "5ca2141da0106d1320c0ae32", detail: 1},
  {_id: "5ca2141da0106d1320c0ae33", detail: 3},
  {_id: "5ca2141da0106d1320c0ae34", detail: 3}
]

arrayOfObjects.forEach(function(obj) {
  Model.update({"_id": obj._id}, {"$set": {"detail": obj.detail}}, callback);
});

UpdateMany数据库.集合集合对象. Refer link .

2izufjch

2izufjch2#

在Mongo 4.2版之前,您必须单独执行每个更新,因为它们有不同的条件,最好使用bulkWrite来完成,以节省网络开销,如下所示:

const input = [
    {_id: ObjectId("5ca2141da0106d1320c0ae32"), detail: 1},
    {_id: ObjectId("5ca2141da0106d1320c0ae33"), detail: 3},
    {_id: ObjectId("5ca2141da0106d1320c0ae34"), detail: 3}
];

const bulk = [];
input.forEach((datum) => {
    bulk.push(
        {
            updateOne: {
                "filter": {_id: datum._id},
                "update": {$set: {detail: datum.detail}}
            }
        }
    )
})

await db.collection.bulkWrite(bulk)

版本4.2引入了pipelined updates,它允许我们在更新主体中使用聚合运算符,现在我们可以执行单个更新并利用此功能,您可以通过多种方式实现更新,下面是一个示例:

const input = [
    {_id: ObjectId("5ca2141da0106d1320c0ae32"), detail: 1},
    {_id: ObjectId("5ca2141da0106d1320c0ae33"), detail: 3},
    {_id: ObjectId("5ca2141da0106d1320c0ae34"), detail: 3}
];

db.collection.updateMany(
    { _id: {$in: input.map(v => v._id )}},
    [
        {
            $set: {
                detail: {
                    $getField: {
                        field: "detail",
                        input: {
                            $first: {
                                $filter: {
                                    input: input,
                                    cond: {
                                        $eq: [
                                            "$$this._id",
                                            "$_id"
                                        ]
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    ])

Mongo Playground

相关问题