简体   繁体   English

MongoDB 根据自定义 ID 更新/删除多个文档

[英]MongoDB Update/delete Multiple documents based on Custom ID

I have a mongo schema我有一个 mongo 架构

   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 .我需要获取具有特定 UserID 的所有文档并更新/删除。 I can use the find method to find all the documents with the required user id .我可以使用 find 方法查找具有所需用户 id 的所有文档。 After that I am at a loss on what to do.There will be multiple documents with same user id .之后我不知道该怎么办。会有多个文件具有相同的用户 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要更新与给定条件匹配的所有文档,请使用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"
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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