【发布时间】:2015-09-02 08:16:46
【问题描述】:
使用包含以下文档的 MongoDB 集合 test:
{ "_id" : 1, "color" : "blue", "items" : [ 1, 2, 0 ] }
{ "_id" : 2, "color" : "red", "items" : [ 0, 3, 4 ] }
如果我根据items 数组中的第二个元素以相反的顺序对它们进行排序,则使用
db.test.find().sort({"items.1": -1})
它们将被正确排序为:
{ "_id" : 2, "color" : "red", "items" : [ 0, 3, 4 ] }
{ "_id" : 1, "color" : "blue", "items" : [ 1, 2, 0 ] }
但是,当我尝试使用 aggregate 函数对它们进行排序时:
db.test.aggregate([{$sort: {"items.1": -1} }])
即使查询被接受为有效,它们也不会正确排序:
{
"result" : [
{
"_id" : 1,
"color" : "blue",
"items" : [
1,
2,
0
]
},
{
"_id" : 2,
"color" : "red",
"items" : [
0,
3,
4
]
}
],
"ok" : 1
}
这是为什么?
【问题讨论】:
标签: mongodb sorting mongodb-query aggregation-framework