一个想法:创建一个单独的cancelled 集合,并将所有已取消的约会移动到此集合中。
如果要进行新的预约,请先搜索此cancelled 集合,以查找因取消而导致的任何空缺。如果没有找到合适的,则按照您当前的方法继续到最远的结束日期。
插图:
> db.appointments.find()
{ "_id" : 0, "start" : 1, "end" : 2, "duration" : 1, "name": "John" }
{ "_id" : 1, "start" : 2, "end" : 4, "duration" : 2, "name": "Jane" }
{ "_id" : 2, "start" : 4, "end" : 5, "duration" : 1, "name": "Jack" }
// Jane cancelled the appt with _id 1
> c = db.appointments.findOne({_id: 1})
> db.cancelled.insert(c)
> db.appointments.deleteOne({_id: 1})
// current state of appointments
> db.appointments.find()
{ "_id" : 0, "start" : 1, "end" : 2, "duration" : 1, "name": "John" }
{ "_id" : 2, "start" : 4, "end" : 5, "duration" : 1, "name": "Jack" }
// Bob wanted to make an appointment spanning two "time units". Is it available?
> db.cancelled.findOne({duration: 2})
{ "_id" : 1, "start" : 2, "end" : 4, "duration" : 2, "name" : "Jane" }
// If Bob agreed to take over Jane's time slot
// reinsert the document from "cancelled" to "appointments", changing the name
> a = db.cancelled.findOne({duration: 2})
> a.name = "Bob"
> db.appointments.insert(a)
> db.cancelled.deleteOne({_id:1})
// end state of appointments
> db.appointments.find().sort({start: 1})
{ "_id" : 0, "start" : 1, "end" : 2, "duration" : 1, "name": "John" }
{ "_id" : 1, "start" : 2, "end" : 4, "duration" : 2, "name": "Bob" }
{ "_id" : 2, "start" : 4, "end" : 5, "duration" : 1, "name": "Jack" }
请注意,在此插图中,我还记录了每个约会的持续时间,以便可以有效地搜索它们。最终状态是来自 Jane 的 _id: 1 被 Bob 替换,cancelled 集合中没有任何内容。
为确保appointments 和cancelled 集合都正确更新,您可能需要使用自MongoDB 4.0 起提供的Transactions。