简体   繁体   English

Mongodb 用不同的值更新多个文档

[英]Mongodb update multiple documents with different values

I have been trying to use updatemany with mongoose.我一直在尝试将updatemanyupdatemany一起使用。 I want to update the values in database using an array of objects.我想使用对象数组更新数据库中的值。

[
            {
                "variantId": "5e1760fbdfaf28038242d676",
                "quantity": 5

            },
            {
                    "variantId": "5e17e67b73a34d53160c7252",
                    "quantity": 13
            }
            ]

I want to use variantId as filter.我想使用 variantId 作为过滤器。 Model schema is:模型架构是:

let variantSchema = new mongoose.Schema({
    variantName: String,
    stocks: {
        type: Number,
        min: 0
    },
    regularPrice: {
        type: Number,
        required: true
    },
    salePrice: {
        type: Number,
        required: true
    }
})

I want to filter the models using variantId and then decrease the stocks.我想使用 variantId 过滤模型,然后减少库存。

As you need to update multiple documents with multiple criteria then .updateMany() wouldn't work - it will work only if you need to update multiple documents with same value, Try this below query which will help you to get it done in one DB call :由于您需要使用多个条件更新多个文档,那么.updateMany()将不起作用 - 只有当您需要更新具有相同值的多个文档时它才会起作用,请尝试以下查询,这将帮助您在一个数据库中完成它称呼 :

const Mongoose = require("mongoose");

let variantSchema = new mongoose.Schema({
    variantName: String,
    stocks: {
        type: Number,
        min: 0
    },
    regularPrice: {
        type: Number,
        required: true
    },
    salePrice: {
        type: Number,
        required: true
    }
})

const Variant = mongoose.model('variant', variantSchema, 'variant');

let input = [
    {
        "variantId": "5e1760fbdfaf28038242d676",
        "quantity": 5

    },
    {
        "variantId": "5e17e67b73a34d53160c7252",
        "quantity": 13
    }
]

let bulkArr = [];

for (const i of input) {
    bulkArr.push({
        updateOne: {
            "filter": { "_id": Mongoose.Types.ObjectId(i.variantId) },
            "update": { $inc: { "stocks": - i.quantity } }
        }
    })
}

Variant.bulkWrite(bulkArr)

Ref : MongoDB-bulkWrite参考: MongoDB-bulkWrite

I don't think this can be done with a single Model.updateMany query.我不认为这可以通过单个Model.updateMany查询来完成。 You will need to loop the array and use Model.update instead.您将需要循环数组并改用Model.update

for (const { variantId, quantity } of objects) {
    Model.update({ _id: variantId }, { $inc: { stocks: -quantity } });
}

To run this in a transaction ( https://mongoosejs.com/docs/transactions.html ), the code should look something like this (however I have not tried or tested this):要在事务 ( https://mongoosejs.com/docs/transactions.html ) 中运行它,代码应该看起来像这样(但是我还没有尝试或测试过):

mongoose.startSession().then(async session => {
    session.startTransaction();

    for (const { variantId, quantity } of objects) {
        await Model.update({ _id: variantId }, { $inc: { stocks: -quantity } }, { session });
    }

    await session.commitTransaction();
});

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

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