首页 > 解决方案 > 同一文档中的 $match expr 不起作用

问题描述

如何使用 $if $else 条件 MongoDB 转换数据

mongo游乐场

我对 $if $expr 条件的研究越来越糟糕

这个游乐场应该什么都不返回,因为日期是 $gt 然后是主集合,但它确实返回了我的数据。

所以条件应该说如果历史的日期是 $gt 那么主集合不应该返回任何其他返回匹配的标准数据。

标签: mongodbaggregation-frameworkconditional-statements

解决方案


history仅使用第一条记录,因为它与集合中的_id相同history_idmain

所以如果你检查第一个历史文件

{
  "_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 部分

注意:我在查询中添加了一些评论,您也可以检查一下吗?


推荐阅读