mongodb $group compare one collection to other collection

こ雲淡風輕ζ 提交于 2020-04-30 06:24:50

问题


I got stuck in one point. See this playground, it should follow this logic:

  • if history's collection is empty, return data
  • if history's date collection is greater then main's collection base on specified user_id, return nothing
  • if specified user_id doesn't match with history's collection date then it should return all data that is in main collection.

So everything looks fine in playground the only problem when i am putting 5e4e74eb380054797d9db623 id it should not return me data because its date is over then main collection


   db.main.aggregate([
      {
        $lookup: {
          from: "history",
          localField: "history_id",
          foreignField: "history_id",
          as: "History"
        }
      },
      {
        $unwind: {
          path: "$History",
          preserveNullAndEmptyArrays: true
        }
      },
      {
        $sort: {
          _id: 1,
          "History.history_id": 1,
          "History.date": 1
        }
      },
      {
        $group: {
          _id: "$_id",
          data: {
            $last: "$$ROOT"
          },
          History: {
            $last: "$History"
          }
        }
      },
      {
        $replaceRoot: {
          newRoot: {
            $mergeObjects: [
              "$data",
              {
                History: "$History"
              }
            ]
          }
        }
      },
      {
        "$match": {
          $expr: {
            $or: [
              {
                $eq: [
                  {
                    $type: "$History.date"
                  },
                  "missing"
                ]
              },
              {
                $ne: [
                  "5e4e74eb380054797d9db623",
                  "$History.user_id"
                ]
              },
              {
                $and: [
                  {
                    $eq: [
                      "5e4e74eb380054797d9db623",
                      "$History.user_id"
                    ]
                  },
                  {
                    $gt: [
                      "$date",
                      "$History.date"
                    ]
                  }
                ]
              }
            ]
          }
        }
      }
    ])

MongoPlayground

来源:https://stackoverflow.com/questions/61504061/mongodb-group-compare-one-collection-to-other-collection

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