相关文章推荐
讲道义的鞭炮  ·  springboot mongodb ...·  2 月前    · 
胆小的香烟  ·  C++ ...·  1 年前    · 
谈吐大方的木瓜  ·  c - CUDA driver API ...·  1 年前    · 
精明的皮带  ·  linux - sftp using ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

The aim that I am trying to achieve:

Update a value in MongoDB based on its current value.

After googling I have found that $cond operator potentially allows me to solve the problem, so I've written the following query:

db.getCollection('product').update({_id: ObjectId("77b2a57556a5e634d57d9977")}, 
{"$set": {"availability" : 
   {$cond: [ { "$availability": { $eq: true } }, "Yes", "No" ] }}});

but for some reason, it doesn't work and MongoDB throws an exception.

So could you please advise: Is it technically the right approach to use $cond within the update query? If yes, why the query doesn't work, semantically it looks good to me,

or possibly some other options on how to solve the problem available, please suggest.

So it seems like you are trying to use Update with Aggregation pipeline which is supported in MongoDB >=4.2. And also if your DB version is >=4.2 the correct syntax would be

db.getCollection("product").update(
  { _id: ObjectId("77b2a57556a5e634d57d9977") },
      $set: {
        availability: {
          $cond: [
              $eq: ["$availability", true],
            "Yes",
            "No",
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.