我有 4 个名为学生、教师、人员和经理的集合,具有相同的猫鼬模式。
const schema = new Schema({
name: String,
age: Number,
email: String
})
如何在一个查询中检索年龄 >=25 的所有学生、职员、经理和教师? 数据应该看起来像 SQL 在联合查询中执行的那样串联。
您可以使用$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供您参考。