Mongodb if then condition under filter how to make

余生长醉 提交于 2020-05-14 14:18:50

问题


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

Play with if condition under filter getting error. My purpose is specified user_id match with history's user_id then condition work other wise not.

How to fix it please guide or alternative approaches are welcome.


回答1:


After discussion in chat, it seems the overall problem was how to select documents from the main collection based on 2 criteria of the related history documents:

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



来源:https://stackoverflow.com/questions/61514726/mongodb-if-then-condition-under-filter-how-to-make

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!