Mongodb:按数组对象对文档进行排序

18 database mongodb nosql

我想按顺序返回文档,其中包含最低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}取所有值的最大值.

  • 你必须仔细观察.第一个结果是上升0,1,1,3.第二个是下降12,9,5,4. (4认同)

小智 0

在 mongo 中没有直接的方法可以做到这一点。您需要使用 map/reduce 来检索每个数组中的最小值,然后按该最小值排序