way to update multiple documents with different values

后端 未结 4 1110
再見小時候
再見小時候 2021-01-17 08:41

I have the following documents:

[{
  \"_id\":1,
  \"name\":\"john\",
  \"position\":1
},
 {\"_id\":2,
  \"name\":\"bob\",
  \"position\":2
},
 {\"_id\":3,
           


        
4条回答
  •  借酒劲吻你
    2021-01-17 08:58

    From mongodb 4.2 you can do using pipeline in update using $set operator

    there are many ways possible now due to many operators in aggregation pipeline though I am providing one of them

        exports.updateDisplayOrder = async keyValPairArr => {
        try {
            let data = await ContestModel.collection.update(
                { _id: { $in: keyValPairArr.map(o => o.id) } },
                [{
                    $set: {
                        displayOrder: {
                            $let: {
                                vars: { obj: { $arrayElemAt: [{ $filter: { input: keyValPairArr, as: "kvpa", cond: { $eq: ["$$kvpa.id", "$_id"] } } }, 0] } },
                                in:"$$obj.displayOrder"
                            
                            }
                        }
                    }
                }],
                { runValidators: true, multi: true }
            )
    
            return data;
        } catch (error) {
            throw error;
        }
       }
    

    example key val pair is [{"id":"5e7643d436963c21f14582ee","displayOrder":9}, {"id":"5e7643e736963c21f14582ef","displayOrder":4}]

提交回复
热议问题