我在一个集合中有以下文档:
{
"thread_object": "Sed consectetur, massa id aliquam lacinia",
"thread_comments": [
{
"comment_date": "11/01/2014 17:23:19",
"comment_user": "Integer",
"comment_content": "In suscipit enim at eleifend auctor"
},
{
"comment_date": "12/01/2014 17:23:19",
"comment_user": "Suspendisse",
"comment_content": "Quisque facilisis magna pellentesque diam mollis"
}
]
},
{
"thread_object": "Vivamus auctor mauris augue",
"thread_comments": []
},
{
"thread_object": "Phasellus volutpat, sem id convallis elementum",
"thread_comments": [
{
"comment_date": "10/01/2014 17:23:19",
"comment_user": "Donec",
"comment_content": "Suspendisse a pellentesque justo"
}
]
}
如何检索所有注释的有序列表?
{
"comment_date": "10/01/2014 17:23:19",
"comment_user": "Donec",
"comment_content": "Suspendisse a pellentesque justo"
},
{
"comment_date": "11/01/2014 17:23:19",
"comment_user": "Integer",
"comment_content": "In suscipit enim at eleifend auctor"
},
{
"comment_date": "12/01/2014 17:23:19",
"comment_user": "Suspendisse",
"comment_content": "Quisque facilisis magna pellentesque diam mollis"
},
您可以使用aggregation framework
展开thread_comments
数组,然后按comment_date
排序。然而,由于日期被存储为String,如果您按comment_date
排序,结果将不被排序。您可能希望使用javascript将comment_date转换为Date()。这里有一个例子。SO上还有其他类似的问题。
假设您已经将comment_date转换为Date(),那么下面的查询就可以工作了:
db.collection.aggregate([
{$unwind:"$thread_comments"},
{$sort:{"thread_comments.comment_date":-1}}
])