2

I have a data as below.

[
  {
    "id": 1,
    "exist": true
  },
  {
    "id": 2,
    "exist": false
  },
  {
    "id": 3,
    "exist": false
  }
]

Only one object can have exist true. So when I findOneAndUpdate({_id:2}),{exist:true}), I hope that exist of 'id:1' is changed to false automatically in one query using aggregate or etc.
could you recommend some idea fot it? Thank you so much for reading my question.

1
  • add your query here Commented Dec 17, 2019 at 7:10

1 Answer 1

1

Starting in MongoDB 4.2, you can use the aggregation pipeline for updates so you can do something like this:

db.your_collection.update(
  {
    $or: [
      {
        id: 2,
        exist: false
      },
      {
        id: {$ne: 2},
        exist: true
      }
    ]
  },
  [{$set: {exist: {$eq: [ "$exist", false ] }}}], 
  {multi: true}
)

Explain:

  • The filter will find records that has id you want and not exist or don't have the id but exist is true. In this case, it will find:

    [
      {
        "id": 1,
        "exist": true
      },
      {
        "id": 2,
        "exist": false
      }
    ]
    
  • The update reverse exist field of found records.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.