简体   繁体   中英

MongoDB Update/delete Multiple documents based on Custom ID

I have a mongo schema

   const taskSchema=new Schema({
    userID:{type:ObjectId,required:true},
  task: {
    type: String,
    required: true,
    trim: true,
    maxlength: 30,
  },
  finalDate:{type:Date,required:true},
  isFinished:{type:Boolean,required:true}
 })

what I need to get all the documents with a particular UserID and update/delete . I can use the find method to find all the documents with the required user id . After that I am at a loss on what to do.There will be multiple documents with same user id . Any ideas on how to proceed will be a great help

Update

To update the first document matching the given condition

db.collection.update({
  "userID": ObjectId("5b87780c9ca8b03096a33380"),
  "task": "Cooking"
},
{
  $set: {
    "isFinished": true
  }
})

Test Here

To update all documents matching the given condition use multi: true

db.collection.update({
  "userID": ObjectId("5b87780c9ca8b03096a33380"),
  "task": "Cooking"
},
{
  $set: {
    "isFinished": true
  }
},
{
  multi: true
})

Test Here

Delete

To delete the first document matching the given condition

db.collection.delete({ 
  "userID": ObjectId("5b87780c9ca8b03096a33380"),
  "task": "Cooking"
})

To delete all documents matching the given condition

db.collection.deleteMany({ 
  "userID": ObjectId("5b87780c9ca8b03096a33380"),
  "task": "Cooking"
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM