Problem referencing field in updateMany

Hello

I have model of this type

const projectSchema = new mongoose.Schema({
	name: String,
        price: Number,
       idCoinMarketCap :Number
});

I would like to change the price of each project with respect to the following variable

let listePriceId = {
        priceId: [
            {
                price: 32000,
                id: 1,
            },
 {
                price: 1700,
                id: 2,
            },

 {
                price: 3000,
                id: 3,
            },

        ]

For this I used uptate to Many

exports.configContract = (req, res) => {


    Project.updateMany(
        {},

        {
            $set: {
                "price": listePriceId.priceId['$idCoinMarketCap']
            },
        },

        (err, response) => {
            if (err) return res.status(500).json({ msg: 'update failed', error: err });
            res.status(200).json({ msg: `document updated`, response: response },

            );

        });

};

It doesn’t work unfortunately

Hello @Mielpops,

For the bulk update you have to use bulkWrite() method, because your every document have own condition/query.

You can use something like this way, I have used updateOne inside bulkWrite(), you can use updateMany if there are multiple matches of idCoinMarketCap field,

exports.configContract = async (req, res) => {
    await Project.bulkWrite([
        {
            updateOne: {
                filter: { idCoinMarketCap: 1 },
                update: { price: 32000 }
            }
        },
        {
            updateOne: {
                filter: { idCoinMarketCap: 2 },
                update: { price: 1700 }
            }
        },
        {
            updateOne: {
                filter: { idCoinMarketCap: 3 },
                update: { price: 3000 }
            }
        }
    ]).then((err, response) => {
        if (err) return res.status(500).json({ msg: 'update failed', error: err });
        res.status(200).json({ msg: `document updated`, response: response });
    });
};

Note: the above code is not tested, prepared from your input.

2 Likes

Hello thank you for your reply
In my example I put only 3 values
but I’m going to have hundreds

You can create a payload same as I have created through the loop and pass it to bulkWrite() method.

3 Likes

Requirements like

should be stated at the beginning since as you have seen the solutions will vary. Luckily, @turivishal’s solution is easily adaptable as he mentioned.

An alternative that could be interesting would be:

  1. create a temporary collection with your price_id_list
  2. perform an aggregation what does a $lookup in the price_id_list
  3. use a final $merge stage to update the price
3 Likes

Hello

thank you both for your answer, I chose the solution of $lookup with $merge.

It works very well, thank you very much

I close the topic

1 Like