mongodb - 同一文档中的 $match expr 不起作用
问题描述
如何使用 $if $else 条件 MongoDB 转换数据
我对 $if $expr 条件的研究越来越糟糕
这个游乐场应该什么都不返回,因为日期是 $gt 然后是主集合,但它确实返回了我的数据。
所以条件应该说如果历史的日期是 $gt 那么主集合不应该返回任何其他返回匹配的标准数据。
解决方案
history
仅使用第一条记录,因为它与集合中的_id
相同history_id
main
所以如果你检查第一个历史文件
{
"_id": ObjectId("5e4e755b380054797d9db627"),
"user_id": "5e4e74eb380054797d9db625",
"history_id": ObjectId("5e4e755b380054797d9db627"),
"date": 1587650683433,
"__v": 1
}
和你的查询
db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "_id",
as: "History"
}
},
{
$unwind: "$History"
},
{
"$match": {
$expr: {
$cond: {
if: {
$eq: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
},
then: {
$and: [
{
$gt: [
"$date",
"$History.date"
]
},
{ // also, this part has no meaning as the same condition is used in the if part
$eq: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
}
]
},
else: {}
}
}
}
}
])
if 条件不满足,因为历史模型中的 user_id"5e4e74eb380054797d9db625"
不等于指定的 id"5e4e74eb380054797d9db623"
因此,它转到获取main
集合中所有文档的 else 部分
注意:我在查询中添加了一些评论,您也可以检查一下吗?
推荐阅读
- database - 如何从 REDCap 中的另一个项目中获取数据
- python - 重塑矩阵
- c# - 在任何基于团队的(工作)项目中重用代码的正确方法是什么?
- dynamics-crm - 模型驱动的 PowerApps 中的正则表达式验证
- android - ListView.builder底部在颤动中按像素溢出
- javascript - 七个圆圈,但只有一个在改变颜色,为什么?
- jquery - jQuery; 验证 asp.net 文本框是否有 19 个字符长度并且是格式
- button - 复选框错误:位置参数太少:
- sql - 根据 SQL 中的多个参数过滤值(多行)
- azure - 如何使用 Azure 函数 Binder 查询运行时指定的表?