mongodb - 给定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 } });
解决方案
您可以使用以下单个查询
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" }}
])
推荐阅读
- java - 在 Spring 中导入安全库时遇到问题
- java-8 - xsd:dateTime 在映射到 java.util.Date 时返回 null
- python - ML:R's Caret 中的大多数模型都可以在 Python 中使用吗?
- java - SupportMapFragment.getMapAsync-NullPointerException
- arrays - 如何在 Matlab 中快速生成多维数组(或张量)?
- javascript - 这个状态管理可以在react上做吗?
- ruby-on-rails-5 - Rspec 应该 AttributeDoesNotExistError
- yammer - Yammer API 根据组 ID #yammer 仅获取我的消息
- vb.net - 部分类继承基类
- javascript - 如何在非 Promise 函数中测试 Promise 回调?