对 MongoDB 中的子文档进行排序 [英] Sort Sub Documents in MongoDB
本文介绍了对 MongoDB 中的子文档进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 mongo 查询中对子文档进行排序?
Is there a way to sort sub documents in a mongo query?
例如:
{
"_id" : ObjectId("4c69d19532f73ad544000001"),
"content" : "blah blah blah",
"comments" : [
{"author": "jim", "content":"comment content 1", "date" : "07-24-1995"},
{"author": "joe", "content":"comment content 2", "date" : "07-24-1996"},
{"author": "amy", "content":"comment content 3", "date" : "09-10-1999"}
]
}
{
"_id" : ObjectId("4c69d19532f73ad544000002"),
"content" : "blah blah blah",
"comments" : [
{"author": "jim", "content":"comment content 1", "date" : "07-24-1995"},
{"author": "joe", "content":"comment content 2", "date" : "07-24-1996"},
{"author": "amy", "content":"comment content 3", "date" : "07-24-1997"}
]
}
我希望以我决定的任何方式对这些文档进行排序,然后按照日期的倒序或我想要的任何其他排序在我的文档中对评论进行排序.
I want these documents to be ordered in however way I decide and then have comments ordered within my a document by reverse order of date or any other sorting I want.
这可以用 mongoDB 实现吗?
Is that possible with mongoDB?
推荐答案
在 mongo 2.4 或更高版本中,您可以在更新时使用 $sort.新的修饰符让您可以对子文档进行排序.
In mongo version 2.4 or above, you can use $sort while updating. The new modifier let you sort sub document.
更多信息可以阅读此页面,http://docs.mongodb.org/manual/reference/operator/sort/一个>
More information could read this page, http://docs.mongodb.org/manual/reference/operator/sort/
这篇关于对 MongoDB 中的子文档进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文