我有一个像这样的数组:
{
"students": [
[
"5c8783f0927b1849b923a47b",
"5c889c139af6b305e19cd17e",
"5c89f1dc4dc6695c138cb2a4",
"5cb0624945111f1c5fdf2527",
"5caed95afd229a5c460e745b",
"5cbeb926fac7143e261adaab"
],
[
"5c8783f0927b1849b923a47b",
"5c889c139af6b305e19cd17e",
"5c89f1dc4dc6695c138cb2a4"
],
[
"5c8783f0927b1849b923a47b",
"5c89f1dc4dc6695c138cb2a4",
"5cadc0452a00532a4c903c38"
],
[
"5c8783f0927b1849b923a47b"
]
]
}
我想找到学生数组中每个数组的大小。 像这样:
"count": [6, 3, 3, 1]
我尝试用$ size尝试$ map
aggregatePipe.push({
$group: {
_id: { subjectId: "$subjectId" },
studentIds: { $push: "$students" },
count: { $push: { $map: { input: "$students", as: "student", in: { $size: "$student" } } } }
}
});
但是我得到的是空值数组。
答案 0 :(得分:3)
您可以使用以下汇总
db.collection.aggregate([
{ "$project": {
"students": {
"$map": {
"input": "$students",
"in": { "$size": "$$this" }
}
}
}}
])
[
{
"_id": ObjectId("5a934e000102030405000000"),
"students": [ 6, 3, 3, 1 ]
}
]
答案 1 :(得分:0)
db.collection.aggregate(
// Pipeline
[
// Stage 1
{
$unwind: {
path: "$students",
}
},
// Stage 2
{
$project: {
count: {
$size: '$students'
}
}
},
// Stage 3
{
$group: {
_id: null,
count: {
$push: '$count'
}
}
},
// Stage 4
{
$project: {
_id: 0
}
},
]
);