首页 > 解决方案 > 给定ID,找到dueAt小于ID.dueAt的条目

问题描述

我正在尝试编写一个查询。我有一个集合Event。每个事件都有一个dueAt数字字段。给定事件的 id,我想找到所有在给定 id 处具有小于事件的 dueAt 的事件。

这是我的意思的例子,我的收藏有这个伪代码:

id: 1,
dueAt: 100

id: 2,
dueAt: 101

id: 3,
dueAt: 102

然后我只有“3”的 id 我想做一个像这样的查询:

eventCollection.find({
    { dueAt: { '<': 'dueAtOfId(3)' }}
});

这种技术有名字吗?任何人都知道他们在 MySQL 中如何称呼它?

我可以在两个查询中轻松地做到这一点,但我想避免学习,伪代码:

const events = await eventCollection.find({ _id: 3 });
const maxDueAt = events[0].dueAt;
const result = await eventCollection.find({ dueAt: { '<': maxDueAt } });

标签: mongodbmongodb-queryaggregation-framework

解决方案


您可以使用以下单个查询

const result = await eventCollection.aggregate([
  { "$match": { "_id": 3 }},
  { "$lookup": {
    "from": "eventCollection",
    "let": { "dueAt": "$dueAt" },
    "pipeline": [
      { "$match": { "$expr": { "$gte": ["$dueAt", "$$dueAt"] }}}
    ],
    "as": "result"
  }},
  { "$unwind": "$result" },
  { "$replaceRoot": { "newRoot": "$result" }}
])

推荐阅读