MongoDB 聚合有两个模型
Posted
技术标签:
【中文标题】MongoDB 聚合有两个模型【英文标题】:MongoDB aggregate with two model 【发布时间】:2021-09-05 01:46:18 【问题描述】:我有两个系列, 班级收藏和学生收藏
class collection
"_id" : "1999558581",
"name" : "Class One",
,
"_id" : "1999558582",
"name" : "Class Two",
,
"_id" : "1999558583",
"name" : "Class Three",
和
student collection
"_id" : "111111",
"First name" : "",
"Last name" : "",
"gender" : "Male",
"class" : "1999558581", //classObjectId
,
"_id" : "111112",
"First name" : "",
"Last name" : "",
"gender" : "Female",
"class" : "1999558581", //classObjectId
,
"_id" : "111113",
"First name" : "",
"Last name" : "",
"gender" : "Male",
"class" : "1999558582", //classObjectId
,
"_id" : "111114",
"First name" : "",
"Last name" : "",
"gender" : "Male",
"class" : "1999558583", //classObjectId
,
"_id" : "111115",
"First name" : "",
"Last name" : "",
"gender" : "Female",
"class" : "1999558581", //classObjectId
我想在一个类中按性别获取聚合,并在类集合中获取名称。
#这是我试过的
const male = await models.Student.aggregate([
$match: gender: "Male" ,
$group: _id: "$class", count: $sum: 1 ,
]).exec();
#制作这个
[
"_id": "60703f09961728430c9656d1",
"count": 9
,
"_id": "60703f09961728430c",
"count": 4
,
"_id": "60703f08430c9656d1",
"count": 13
,
]
这个“_id”:“60703f09961728430c9656d1”,是类集合中的Id,所以我想得到这个_id关联的名字
[
"_id": "60703f09961728430c9656d1",
"name" : "Class One"
"count": 9
,
"_id": "60703f09961728430c",
"name" : "Class Two"
"count": 4
,
"_id": "60703f08430c9656d1",
"name" : "Class Three"
"count": 13,
,
]
【问题讨论】:
【参考方案1】:您可以同时使用 $group 和 $lookup,这可能会解决您的问题。
const male = await models.Student.aggregate([
$match: gender: "Male" ,
$group: _id: "$class", count: $sum: 1 ,
$lookup: from: "class", localField: "_id", foreignField: "_id", as: "class"
]).exec()
【讨论】:
以上是关于MongoDB 聚合有两个模型的主要内容,如果未能解决你的问题,请参考以下文章
使用 $unwind、$lookup 和 $group 的复杂聚合中的 mongodb 正确列表顺序