Mongodb如果然后在过滤器下条件如何制作

问题描述 投票:0回答:1
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"
  }
])

MongoPlayground

在过滤器出现错误的情况下播放。我的目的是指定user_id与历史记录的user_id匹配,然后不进行其他条件的工作。

如何修复它,请指导或欢迎使用其他方法。

mongodb filter mongodb-query aggregation-framework conditional-statements
1个回答
0
投票

在聊天中讨论之后,似乎总的问题是如何根据相关历史文档的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"
                      ]}
                  ]}
                ]
              }
          }}
        ]
      }
  }}
])

Playground

© www.soinside.com 2019 - 2024. All rights reserved.