这个问题已经在这里有了答案: > how to sort array inside collection record in mongoDB 14个
> MongoDB sort documents by array elements 1个
我正在尝试使用称为orderIndex的嵌套字段对数据进行排序.
router.get("/", (req, res) => {
Book.find({ _id: req.params.id })
.sort({ 'Book.chapters.orderIndex': "asc" }) //doesn't work
.then(books => {
res.render("books/index", {
books: books
})
});
});
一本书的外观示例:
//Book
{
"_id": {
"$oid": "1234517fe46cf86900af82f"
},
"chapters": [
{
"_id": {
"$oid": "a1"
},
"title": "first book",
"orderIndex": "1",
},
{
"_id": {
"$oid": "5678798be6bb05e4427ee65"
},
"title": "second book",
"orderIndex": "2",
},
//..some more
]
}
解决方法:
更改
.sort({ 'Book.chapters.orderIndex': "asc" })
至
.sort({ 'chapters.orderIndex': 1 })
看看这个link
这里是sort
文档.