Home > Software design >  mongoose: updateMany with $and does not work properly
mongoose: updateMany with $and does not work properly

Time:10-21

db.dbDB.collection("buy").updateMany(
  {
    $and: [
      { profit: { $eq: null } },
      { tp_buy: { $gte: incomingData.bid } },
    ],
  },
  {
    $set: {
      profit: true,
      execute_p: incomingData.bid,
    },
  }
);

I have this updateMany() function.

{
    "_id" : ObjectId("asdfeasd"),
    "profit" : true,
    "tp_buy" : 1.16583,
    "execute_p" : 1.16487
}

However, as it shows my db is updated even though the incomingData.bid has not exceed the tp_buy.

Before, modifying profit, it is valued as null.

Console.logging incomingData.bid returns number and tp_buy is stated as double on MongoDB.

How can I only update when the document has a profit value null and incomingData.bid is greater than tp_buy?

CodePudding user response:

Query

  • i think you have the comparison wrong, try this if you can
  • instead of 1.2 put the incomingData.bid
  • incomingData.bid > tp_buy is like tp_buy< incomingData.bid

Test code here

db.collection.update({
  $and: [
    {
      profit: {
        $eq: null
      }
    },
    {
      tp_buy: {
        $lt: 1.2
      }
    },
    
  ],
  
},
{
  $set: {
    profit: true,
    execute_p: 1.2,
    
  },
  
})
  • Related