首页 > 解决方案 > 如何使用 $groupby 和转换不同的值 mongodb

问题描述

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

这个操场应该返回两个属于“tester 2”和“tester 3”文本的对象,如果我在历史集合中有多个对象,它还应该检查最后一个对象,而不是所有对象如何可能

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

db.main.aggregate([
  {
    $lookup: {
      from: "history",
      localField: "history_id",
      foreignField: "history_id",
      as: "History"
    }
  },
  {
    $unwind: "$History"
  },
  {
    "$match": {
      $expr: {
        $cond: {
          if: {
            $eq: [
              "5e4e74eb380054797d9db623",
              "$History.user_id"
            ]
          },
          then: {
            $and: [
              {
                $gt: [
                  "$date",
                  "$History.date"
                ]
              },
              {
                $eq: [
                  "5e4e74eb380054797d9db623",
                  "$History.user_id"
                ]
              }
            ]
          },
          else: {}
        }
      }
    }
  }
])

Mongo游乐场

标签: mongodbaggregation-frameworkconditional-statements

解决方案


如果我对您的理解正确,这就是您要执行的操作:

db.main.aggregate([
  {
    $lookup: {
      from: "history",
      let: {
        main_history_id: "$history_id",
        main_user_id: { $toString: "$sender_id" }
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$history_id",
                    "$$main_history_id"
                  ]
                },
                {
                  $eq: [
                    "$user_id",
                    "$$main_user_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"
                ]
              },
              {
                $gte: [
                  "$date",
                  "$History.date"
                ]
              }
            ]
          }
        ]
      }
    }
  }
])

Mongo游乐场


推荐阅读