对于specific事件(有开始/结束日期),我可以check if there is an overlapping event.

我如何列出all个重叠的事件?

例如,用于:

ID start end note
1 2023-08-16 10:00 2023-08-16 12:00
2 2023-08-16 12:00 2023-08-16 14:00
3 2023-08-16 14:00 2023-08-16 16:00
4 2023-08-16 11:00 2023-08-16 14:00 overlaps with 1 and 2
5 2023-08-16 12:30 2023-08-16 12:40 overlaps with 2 and 4

Should either return all affected events: 1,2,4,5
Or the highest ID's that are causing the overlaps: 4,5

注意:日期实际上是Date对象,但在此表中显示为字符串.

在MySQL this中,我将如何做到这一点:

SELECT *,
       EXISTS (SELECT 1
               FROM events AS other
               WHERE other.event_id < events.event_id
                 AND other.end > events.start
                 AND other.start < events.end) AS conflict
FROM events

如何在MongoDB中实现类似的功能?

推荐答案

类似查询的一个选项是使用$lookup:

db.events.aggregate([
  {$lookup: {
      from: "events",
      let: {id: "$ID", start: "$start",  end: "$end"},
      pipeline: [
        {$match: {$expr: {$and: [
                {$lt: ["$ID", "$$id"]},
                {$lt: ["$start", "$$end"]},
                {$gt: ["$end", "$$start"]}
        ]}}}
      ],
      as: "conflicts"
  }},
  {$match: {"conflicts.0": {$exists: true}}},
  {$project: {_id: 0, ID: 1, notes: "$conflicts.ID"}}
])

看看它在playground example号公路上是如何工作的

Mongodb相关问答推荐

MongoDB:如何通过增量向量递增整数向量

MongoDB/Mongoose查询:使用优先约束检索从位置A到位置B的路径

DTO 验证适用于 POST,但不适用于 PUT

Mongo,通过 Lookup 计算多个文档中数组中的项目

对对象数组进行分组并在 mongodb 中获取计数

mongoDB中数组中的聚合和元素

使用 $addFields 将字段添加到 $lookup 结果中的每个项目

使用 homebrew 和 Xcode 8.1.1 安装 Mongodb 失败

如何在 Mongo 聚合中合并文档中的数组字段

Mongo查询子文档的多个字段

指定字段对于 MongoDB 是transient瞬态的,但对于 RestController 不是

使用 mgo 存储嵌套 struct

字段类型在 MongoDB 索引中是否重要?

Express 无法 PUT/DELETE 方法.出了什么问题?

MongoDB:单个数据库处理程序的 >5 个打开连接

MongoDB:在集合上设置 TTL 索引时出错: sessions

MongoDB Java API:put() 与 append()

从 id 删除 PyMongo 中的文档

如何在 MongoDB Map-reduce 映射函数中使用变量

findOneAndUpdate 中的文档未更新