mongodb - Mongodb if then 条件下过滤器如何制作
问题描述
db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}
},
{
$project: {
"History": {
$filter: {
input: "$History",
as: "his",
if: {
$eq: [
"5e4a8d2d3952132a08ae5764",
"$$his.user_id"
]
},
then: {
cond: {
$and: [
{
$lt: [
"$$his.date",
"$date"
]
},
{
$eq: [
"5e4a8d2d3952132a08ae5764",
"$$his.user_id"
]
}
]
}
},
else: {}
}
},
data: 1,
history_id: 1,
sender_id: 1,
text: 1,
date: 1
}
},
{
$unwind: "$History"
}
])
在过滤器出现错误时使用 if 条件。我的目的是指定 user_id 与历史的 user_id 匹配,然后条件工作否则不。
如何解决它,请指导或欢迎替代方法。
解决方案
在聊天讨论之后,似乎总体问题是如何根据相关历史文档的 2 个标准从主集合中选择文档:
db.main.aggregate([
{$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}},
{$match: {
$expr: {
$eq: [
false,
{$reduce: {
input: "$History",
initialValue: false,
in: {
$or: [
"$$value",
{$and: [
{$eq: [
"$$this.user_id",
ObjectId("5e4a8d2d3952132a08ae5764")
]},
{$gte: [
"$$this.date",
"$date"
]}
]}
]
}
}}
]
}
}}
])
推荐阅读
- mysql - 如何在 MySql docker 映像中运行 Django 种子数据?
- c# - 如何通过 API 设置 webhook URL
- c - 在c中的预处理器时间内获取定义值
- bash - linux读取命令 - 什么未使用,丢弃?
- c++ - 将 std::string_view 返回到 const char *
- python - 如何定期对格子行的元素求和
- flutter - 如何在 Flutter 中的盒子装饰上的图像上添加不透明覆盖
- go - 在golang中连接两个地图
- c++ - 根中的空 TH2F 直方图
- flutter - 如何在 Flutter 上实现 Material Speed Dial?