Mongodb:按数组对象排序文档 [英] Mongodb: sort documents by array objects
问题描述
我想按照排序的顺序返回文档,其中保存最低的 foo.bar
值(它们是数组对象)。
我可以做 db.collection.find()。sort({foo.0.bar:1})
,但这只匹配数组中的第一个元素 - 并且你可以看到在下面的例子中,首先排序项目1(foo.0.bar = 5),wheras我寻找返回项目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
}
]
}
解决方案似乎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}]}}
并运行以下命令:
db.collection.find({})。sort({abc:1});
//产生:
{a:{b:[{c:0},{c:12}]}}
{a:{b:[{c:1} {c:5}]}}
{a:{b:[{c:1},{c:9}]}}
{a:{b: {c:3}]}}
db.collection.find({})。sort({abc: - 1});
//产生:
{a:{b:[{c:0},{c:12}]}}
{a:{b:[{c:1} {c:9}]}}
{a:{b:[{c:1},{c:5}]}}
{a:{b: {c:3}]}}
正如你所看到的, > {abc:1} 使用数组中所有值的最小,并排序,而
{abc :-1}
使用所有值的最大。I would like to return the documents in an order sorted by which holds the lowest
foo.bar
value (which are array objects).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 } ] }
解决方案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 } ] } }
And run the following:
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 } ] } }
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屋!