gpt4 book ai didi

node.js - 如何在数组中查找数组的大小?

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

我有一个像这样的数组:

{
"students": [
[
"5c8783f0927b1849b923a47b",
"5c889c139af6b305e19cd17e",
"5c89f1dc4dc6695c138cb2a4",
"5cb0624945111f1c5fdf2527",
"5caed95afd229a5c460e745b",
"5cbeb926fac7143e261adaab"
],
[
"5c8783f0927b1849b923a47b",
"5c889c139af6b305e19cd17e",
"5c89f1dc4dc6695c138cb2a4"
],
[
"5c8783f0927b1849b923a47b",
"5c89f1dc4dc6695c138cb2a4",
"5cadc0452a00532a4c903c38"
],
[
"5c8783f0927b1849b923a47b"
]
]
}

我想找到学生数组中每个数组的大小。像这样:

"count": [6, 3, 3, 1]

我试过 $map 和 $size

 aggregatePipe.push({
$group: {
_id: { subjectId: "$subjectId" },
studentIds: { $push: "$students" },
count: { $push: { $map: { input: "$students", as: "student", in: { $size: "$student" } } } }
}
});

但我得到的是空值数组。

最佳答案

您可以使用以下聚合

db.collection.aggregate([
{ "$project": {
"students": {
"$map": {
"input": "$students",
"in": { "$size": "$$this" }
}
}
}}
])

Output

[
{
"_id": ObjectId("5a934e000102030405000000"),
"students": [ 6, 3, 3, 1 ]
}
]

关于node.js - 如何在数组中查找数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56471940/

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