您可以使用聚合框架的$unwind 运算符将数组展开为多个文档。
db.fruits.aggregate(
{$unwind: "$sort"},
{$sort: {sort: 1}}
)
该$unwind
操作通过创建多个文档来“展开”文档上的数组,每个文档对应该数组中的每个值。然后,我们只是根据给定的标准进行排序。所以对于输入:
> db.fruits.insert({sort:[1,2,4,6], fruit:'apple'})
> db.fruits.insert({sort:[3], fruit:'cherry'})
> db.fruits.insert({sort:[5], fruit:'orange'})
我们得到结果输出:
> db.fruits.aggregate({$unwind: "$sort"}, {$sort: {sort: 1}})
{
"result" : [
{
"_id" : ObjectId("51f0592c8a542caf3f07fa66"),
"sort" : 1,
"fruit" : "apple"
},
{
"_id" : ObjectId("51f0592c8a542caf3f07fa66"),
"sort" : 2,
"fruit" : "apple"
},
{
"_id" : ObjectId("51f059358a542caf3f07fa67"),
"sort" : 3,
"fruit" : "cherry"
},
{
"_id" : ObjectId("51f0592c8a542caf3f07fa66"),
"sort" : 4,
"fruit" : "apple"
},
{
"_id" : ObjectId("51f0593b8a542caf3f07fa68"),
"sort" : 5,
"fruit" : "orange"
},
{
"_id" : ObjectId("51f0592c8a542caf3f07fa66"),
"sort" : 6,
"fruit" : "apple"
}
],
"ok" : 1
}
如果您需要维护原始排序数组,您可以使用$project
创建原始文档的投影,将排序字段复制到一个expanded_sort
字段中,然后展开该字段,如下所示:
db.fruits.aggregate(
{$project: {sort: 1, fruit: 1, expanded_sort: "$sort"}},
{$unwind: "$expanded_sort"},
{$sort: {expanded_sort: 1}}
)
这会让你得到这样的结果:
"result" : [
{
"_id" : ObjectId("51f0592c8a542caf3f07fa66"),
"sort" : [ 1, 2, 4, 6 ],
"fruit" : "apple",
"expanded_sort" : 1
},