我想按顺序返回文档,其中包含最低foo.bar值(即数组对象).
我可以做db.collection.find().sort({foo.0.bar: 1}),但这只匹配数组中的第一个元素 - 正如你在下面的例子中看到的那样,首先对第1项进行排序(foo.0.bar = 5),我希望首先返回第2项,(foo.2.bar = 4)因为它具有最低值的对象.
{
"name": "Item 1",
"foo": [
{
"bar": 5
},
{
"bar": 6
},
{
"bar": 7
}
]
}
{
"name": "item 2",
"foo": [
{
"bar": 6
},
{
"bar": 5
},
{
"bar": 4
}
]
}
Run Code Online (Sandbox Code Playgroud) 有没有办法在mongo查询中对子文档进行排序?示例(博客集合):
{
"_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"}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望按照我决定的方式订购我的博客文章,然后在我的博客帖子中通过按日期反向排序或我想要的任何其他排序来订购评论.这可能与mongoDB有关吗?
我的数据如下所示:
{
"name":"dan",
"somestring":"asdf",
"friends":[
{
"name": "carl",
"height":180,
...
},
{
"name": "john",
"height":165,
...
},
{
"name": "jim",
"height":170,
...
}
]
},
...
Run Code Online (Sandbox Code Playgroud)
我想检索朋友按高度降序排序的文档。
我试过了,db.getCollection('users').find({"name" : "dan"}, {"friends" : 1}).sort({"friends.height" : -1})但朋友列表保持不变。
编辑:我搞砸了我的数据结构,我修复了数组看起来像一个数组......
该.sort()功能似乎对我根本不起作用,它不会对我所做的任何事情进行排序。
我通过 Handlebars {{Book}} 显示输出
router.get("/", (req, res) => {
Book.find({ _id: req.params.id })
.sort({ 'chapters.orderIndex': 1 }) //wont sort
.then(books => {
res.render("books/index", {
books: books
})
});
});
Run Code Online (Sandbox Code Playgroud)
我也试过:
.sort({ 'Book.chapters.orderIndex': 1 })
.sort({ 'Book.date': 1 })
.sort({ 'date': 1 }) //field from Book
.sort({ date: 1 })
Run Code Online (Sandbox Code Playgroud)
也尝试过asc/desc而不是使用1/-1
知道为什么.sort()不起作用吗?
我正在尝试使用嵌套字段对数据进行排序,称为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
})
});
});
Run Code Online (Sandbox Code Playgroud)
Book外观示例:
//Book
{
"_id": {
"$oid": "1234517fe46cf86900af82f"
},
"chapters": [
{
"_id": {
"$oid": "a1"
},
"title": "first book",
"orderIndex": "1",
},
{
"_id": {
"$oid": "5678798be6bb05e4427ee65"
},
"title": "second book",
"orderIndex": "2",
},
//..some more
]
}
Run Code Online (Sandbox Code Playgroud)