Home > Mobile >  upsert with $set if not null mongodb
upsert with $set if not null mongodb

Time:05-27

Suppose a I have a collection of document structure.

   {
      uuid: "157071f4-2624-4c49-8735-bd345425a16b",
      price: {
          item1: 20,
          item2: 30
     } 
   }

Now I want to upsert data based on uuid, using something like

await Coll.findOneAndUpdate({uuid}, {$set: {[`price.${itemNo}`]: 40}, {upsert: true}}

My issue is that $set here update values even in cases where itemNo already exists. And if I put a check on query, something like,

{uuid, [`price.${itemNo}`]: {$exists: 0}}

then it creates a new document due to upsert even if uuid exists.

My end goal is to achieve upsert if uuid doesn't exist and and if uuid exists then don't update the value for "price.item" if it also exists else set the value. Some thing like $setOnInsert also doesn't meet the requirement I only need to update the value. Thanks in advance.

CodePudding user response:

Got the solution. We can achieve this by first defining our update field something like:

let fieldName = `price.${itemNo}`

Then doing something like:

await Coll.findOneAndUpdate({
   uuid
},
[{
    $set: {
        [fieldName]: {
                $cond: [{
                    $or: [
                        {$ne: ["$price", null]},
                        {$ne: [`$${fieldName}`, null]}
                    ]
                }, valueToBeSet, `$${fieldName}`]
        }
    }
}], {upsert: true}
      
  • Related