【发布时间】:2021-07-09 04:33:16
【问题描述】:
我阅读了文档,发现 addToSet 不保证顺序。 但是有什么办法可以将订单保留为原始文档。 我的查询是:-
aggregate([{$match: {
$or:[{"Name.No":"119"},{"Name.No":"120"}]
}}, {$project: {
x:{$objectToArray:"$Results"}
}},{$unwind: "$x"},{$group: {_id: "$x.k", distinctVals: {$addToSet: "$x.v.TCR"}}}])
样本数据:
{"Name" : {"No." : "119","Time" : "t"},
"Results":{"K1" : {"Counters" : x, "TCR" : [{"Name" : "K11", "Result" : "PASSED"},
{"Name" : "K12","Result" : "FAILED"},
{"Name" : "K13","Result" : "PASSED"}]
},
"K2" : {"Counters": y, "TCR" : [{"Name" : "K21","Result" : "PASSED"},
{"Name" : "K22","Result" : "PASSED"}]
}
}
}
} 工作2;
{"Name" : {"No." : "120","Time" : "t1"},
"Results":{"K1" : {"Counters" : x, "TCR" : [{"Name" : "K11", "Result" : "PASSED"},
{"Name" : "K12","Result" : "PASSED"},
{"Name" : "K13","Result" : "FAILED"}]
},
"K3" : {"Counters": y, "TCR" : [{"Name" : "K31","Result" : "PASSED"},
{"Name" : "K32","Result" : "PASSED"}]
}
}
} 预期;
{"Name" : {"No." : "119-120","Time" : "lowest(t,t1)"},
"Results":{"K1" : {"Counters" : x, "TCR" : [{"Name" : "K11", "Result" : "PASSED"},
{"Name" : "K12","Result" : "PASSED"},
{"Name" : "K13","Result" : "PASSED"}]
},
"K2" : {"Counters": y, "TCR" : [{"Name" : "K21","Result" : "PASSED"},
{"Name" : "K22","Result" : "PASSED"}]
},
"K3" : {"Counters": y, "TCR" : [{"Name" : "K31","Result" : "PASSED"},
{"Name" : "K32","Result" : "PASSED"}]
}
}
} 我想保持与原始文档相同的顺序,而且每次文档都会更改,所以我无法根据任何参数进行排序。
【问题讨论】:
-
您能否在查询中添加示例数据mongoplayground.net
-
如何定义顺序?假设您输入的是
[20, 10, 20]。你想得到什么输出?[10, 20]还是[20,10]?来自@turivishal 的解决方案给出了[20,10] -
添加了现在有问题的示例数据。
标签: mongodb mongoose mongodb-query aggregation-framework