我想按顺序返回文档,其中包含最低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)
小智 19
似乎mongo 可以做到这一点.
例如,如果我有以下文件:
{ a:{ b:[ {c:1}, {c:5 } ] } }
{ a:{ b:[ {c:0}, {c:12} ] } }
{ a:{ b:[ {c:4}, {c:3 } ] } }
{ a:{ b:[ {c:1}, {c:9 } ] } }
Run Code Online (Sandbox Code Playgroud)
并运行以下内容:
db.collection.find({}).sort({ "a.b.c":1 });
// produces:
{ a:{ b:[ {c:0}, {c:12} ] } }
{ a:{ b:[ {c:1}, {c:5 } ] } }
{ a:{ b:[ {c:1}, {c:9 } ] } }
{ a:{ b:[ {c:4}, {c:3 } ] } }
db.collection.find({}).sort({ "a.b.c":-1 });
// produces:
{ a:{ b:[ {c:0}, {c:12} ] } }
{ a:{ b:[ {c:1}, {c:9 } ] } }
{ a:{ b:[ {c:1}, {c:5 } ] } }
{ a:{ b:[ {c:4}, {c:3 } ] } }
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,sort by {"a.b.c":1}取数组中所有值的min并对其进行排序,而sort by {"a.b.c":-1}取所有值的最大值.
| 归档时间: |
|
| 查看次数: |
15055 次 |
| 最近记录: |