【发布时间】:2019-01-04 09:47:35
【问题描述】:
我在 mongodb 聚合管道中对数组进行排序时遇到问题。我在 stackoverflow 中找不到答案,所以我发布了我的问题
我在 mongodb 中有一些具有这种结构的数据
{
testOne:{ scores:[1, 5, 8]},
testTwo:{scores:[3, 4, 5]},
testThree:{scores:[9,0,1]},
........
testFifty:{scores:[0,8,1]}
}
基本上是一系列的许多测试和这些测试的分数(这是一个说明问题的简化示例)。
头撞墙几个小时后,我发现我只能展开两个数组,再展开,也没有返回任何数据。
所以我无法展开所有数组和分组以从数据库中获取每个测试分数的数组
db.collection.aggregate([
{
{$unwind: '$testOne.scores'},
{$unwind: '$testTwo.scores'},
{$unwind: '$testThree.scores'},
{$group:{
_id: {},
concatTestOne: { $push: "$testOne.scores"},
concatTestTwo: { $push: "$testTwo.scores"},
concatTestThree: { $push: "$testThree.scores"}
}
}
令我沮丧的是,即使我只是展开,结果数组也没有正确排序,请参见下文:
db.collection.aggregate([
{
{$unwind: '$testOne.scores'},
{$group:{
_id: {},
concatTestOne: { $push: "$testOne.scores"}
}
{$sort:{concatTestOne: 1}},
}
结果是 [1,5,8,3,4,5,....,9,0,1]。没有排序
因此,为了获得所有测试分数,我使用 reduce 来展平分组阶段产生的嵌套数组,没有“展开”,例如:
db.collection.aggregate([
{
{$group:{
_id: {},
concatTestOne: { $push: "$testOne.scores"}
},
{$addFields:{
testOneScores: {$reduce: {
input: "$concatTestOne",
initialValue: [ ],
in: { $concatArrays: [ "$$value", "$$this" ] }
}
}
}
结果数组再次没有排序。谁能告诉我我做错了什么。数组很大(长度约为 3500)只是 mongoDB 聚合不处理大型数组吗?
非常感谢任何 cmets 我花了很多时间尝试对我的数组进行排序并注意到到目前为止的工作
【问题讨论】:
标签: mongodb aggregation-framework