gpt4 book ai didi

mongodb - $lookup 结果的计数 mongodb

转载 作者:可可西里 更新时间:2023-11-01 09:08:41 25 4
gpt4 key购买 nike

将 mongodb 与 NodeJS 驱动程序结合使用

我有 2 个收藏。一个给部门,另一个给学生。

Deparmtent 的示例数据。

{ 
"_id" : ObjectId("5a24d20590d3d12155f3094e"), "name" : "CSE", "hod" :
"abc",
"students" : [
ObjectId("5a2129172c3e542acb78c1f5"),
ObjectId("5a2129172c3e542acb78c1f7"),
ObjectId("5a2129172c3e542acb78c1f9"),
ObjectId("5a2129172c3e542acb78c1fb")
]
}

{
"_id" : ObjectId("5a24d20590d3d12155f3094f"),
"name" : "IT",
"hod" : "xyz", ,
"students" : [
ObjectId("5a2129172c3e542acb78c1f6"),
ObjectId("5a2129172c3e542acb78c1f8"),
ObjectId("5a2129172c3e542acb78c1fa"),
ObjectId("5a2129172c3e542acb78c1fc")
]
}

和学生的示例数据

{
"_id" : ObjectId("5a2129172c3e542acb78c1f4"),
"rollNumber" : 11,
"name" : "Thor",
"branch" : ObjectId("5a24d20590d3d12155f3094e"),
}

这里是查询:

aggregate([
{$lookup:
{ from: "students",
localField: "_id",
foreignField: "branch",
as: "studentData"
}
}
])

查询的输出

[ 
{ _id: 5a24d20590d3d12155f3094e,
name: 'CSE',
hod: 'abc',
studentData: [ [Object], [Object], [Object], [Object], [Object] ]
},
{ _id: 5a24d20590d3d12155f3094f,
name: 'IT',
hod: 'xyz',
studentData: [ [Object], [Object], [Object], [Object] ] }
]

我有两个问题

  1. 如何打印完整的学生数据。
  2. 如何获取每个系的studentData数量

最佳答案

要获得完整的学生数据,您可以执行以下操作

db.student.aggregate(
[
{
$lookup:
{
from:"department",
localField:"branch",
foreignField:"_id",
as:"branch"
}
}
]
)

这会给你这样的东西:

{
"_id" : 1.0,
"rollNumber" : 110.0,
"name" : "Thor",
"branch" : [
{
"_id" : 1.0,
"name" : "CSE",
"hod" : "abc"
}
]
}

获取每个系的studentData数量

db.getCollection('student').aggregate(
[
{
$lookup:
{
from:"department",
localField:"branch",
foreignField:"_id",
as:"branch"
}
},
{
$group:
{
_id:"$branch",
"numOfStudent":{$sum:1},
"listOfStudents":{$push:"$name"}
}
}
]
)

这会给你这样的东西:

{
"_id" : [
{
"_id" : 2.0,
"name" : "IT",
"hod" : "xyz"
}
],
"numOfStudent" : 1.0,
"listOfStudents" : [
"Ironman2"
]
}
{
"_id" : [
{
"_id" : 1.0,
"name" : "CSE",
"hod" : "abc"
}
],
"numOfStudent" : 3.0,
"listOfStudents" : [
"Thor",
"Ironman",
"Ironman3"
]
}

如果您想存储学生的 ID 而不是他们的名字,您可以将 $push:$name 更改为 $push:$_id

编辑使用“部门”集合获得类似的结果:

db.department.aggregate([
{
$lookup:
{
from:"student",
localField:"students",
foreignField:"_id",
as:"studentsDetails"
}
},
{
$project:{
_id:0,
name:"$name",
hod:"$hod",
numOfStudents:{$size:"$studentsDetails"},
students:"$studentsDetails"
}
}
])

这会给你这样的东西:

{
"name" : "CSE",
"hod" : "abc",
"numOfStudents" : 2,
"students" : [
{
"_id" : 1.0,
"rollNumber" : 110.0,
"name" : "Thor",
"branch" : 1.0
},
{
"_id" : 3.0,
"rollNumber" : 111.0,
"name" : "Ironman2",
"branch" : 2.0
}
]
}

关于mongodb - $lookup 结果的计数 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47627701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com