使用 Mongoose 进行多集合连接/连接查询,类似于 SQL 中的联合查询

问题描述 投票:0回答:1

我有 4 个名为学生、教师、人员和经理的集合,具有相同的猫鼬模式。

const schema = new Schema({
    name: String,
    age: Number,
    email: String
})

如何在一个查询中检索年龄 >=25 的所有学生、职员、经理和教师? 数据应该看起来像 SQL 在联合查询中执行的那样串联。

mongodb mongoose mongodb-query aggregation-framework
1个回答
1
投票

您可以使用$unionWith。在

pipeline
中指定年龄 >= 25 标准。

db.students.aggregate([
  {
    $match: {
      age: {
        $gte: 25
      }
    }
  },
  {
    "$unionWith": {
      "coll": "teachers",
      "pipeline": [
        {
          $match: {
            age: {
              $gte: 25
            }
          }
        }
      ]
    }
  },
  {
    "$unionWith": {
      "coll": "stuffs",
      "pipeline": [
        {
          $match: {
            age: {
              $gte: 25
            }
          }
        }
      ]
    }
  },
  {
    "$unionWith": {
      "coll": "managers",
      "pipeline": [
        {
          $match: {
            age: {
              $gte: 25
            }
          }
        }
      ]
    }
  }
])

这里是Mongo Playground供您参考。

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