Mongodb:按数组对象对文档进行排序 [英] Mongodb: sort documents by array objects
问题描述
我想按包含最低 foo.bar
值(它们是数组对象)的排序顺序返回文档.
I would like to return the documents in an order sorted by which holds the lowest foo.bar
value (which are array objects).
我可以执行 db.collection.find().sort({foo.0.bar: 1})
,但这仅匹配数组中的第一个元素 - 正如您所见在下面的示例中,将首先对项目 1 进行排序(foo.0.bar = 5),而我希望首先返回项目 2 (foo.2.bar = 4)
,因为它具有对象最低值.
I can do db.collection.find().sort({foo.0.bar: 1})
, but this only matches the first element in the array - and as you can see in the exampe below would sort item 1 first (foo.0.bar = 5), wheras I am looking to return item 2 first (foo.2.bar = 4)
as it has the object with the lowest value.
{
"name": "Item 1",
"foo": [
{
"bar": 5
},
{
"bar": 6
},
{
"bar": 7
}
]
}
{
"name": "item 2",
"foo": [
{
"bar": 6
},
{
"bar": 5
},
{
"bar": 4
}
]
}
推荐答案
看来 mongo 可以做到这一点.
It seems mongo can do this.
例如,如果我有以下文件:
For example, if I have the following documents:
{ a:{ b:[ {c:1}, {c:5 } ] } }
{ a:{ b:[ {c:0}, {c:12} ] } }
{ a:{ b:[ {c:4}, {c:3 } ] } }
{ a:{ b:[ {c:1}, {c:9 } ] } }
然后运行以下命令:
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 } ] } }
如您所见,{"abc":1}
排序采用数组中所有值的 min 并对其进行排序,而 sort by{"abc":-1}
取所有值的 max.
As you can see, the sort by {"a.b.c":1}
takes the min of all values in the array and sorts on that, whereas the sort by {"a.b.c":-1}
takes the max of all the values.
这篇关于Mongodb:按数组对象对文档进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!