Mongo按数组

时间:2017-12-05 06:25:11

标签: arrays mongodb sorting

我有一份学生名单。每个人都有一个点数组,他们在一个名为lightTrail的数组中按类别获得。我想要在lightTrail数组中索引1处显示最多行为点的前5个人。如果是平局,则第二个排序字段是它们在索引0处显示的总点数。

以下是我的尝试:

db.students.aggregate([{
        $project: {
            fname: 1,
            surname: 1,
            lightTrails: 1,
            '_id': 0
        }
    },
    {
        $sort: {
            "lightTrails.1": -1,
            "lightTrails.0": -1
        }
    }, {
        $limit: 5
    }
], {
    allowDiskUse: true
})

这是我想要的结果:

{
    "fname": "Jim",
    surname: "Jones",
    lightTrails: [200, 70, 30, 30, 15, 15, 40]
}, {
    "fname": "Sean",
    surname: "Marx",
    lightTrails: [180, 50, 50, 20, 20, 15, 25]
}, {
    "fname": "Todd",
    surname: "Lull",
    lightTrails: [150, 40, 60, 15, 15, 10, 10]
}, {
    "fname": "Flynn",
    surname: "Moore",
    lightTrails: [100, 40, 25, 15, 5, 10, 5]
}, {
    "fname": "Al",
    surname: "Ryan",
    lightTrails: [80, 20, 20, 10, 10, 10, 10]
}

我得到的结果只有5名学生没有订单:

{
  "fname": "Flynn",
    surname: "Moore",
      lightTrails: [100, 40, 25, 15, 5, 10, 5]
}, {
  "fname": "Jim",
    surname: "Jones",
      lightTrails: [200, 70, 30, 30, 15, 15, 40]
}, {
  "fname": "Al",
    surname: "Ryan",
      lightTrails: [80, 20, 20, 10, 10, 10, 10]
}, {
  "fname": "Todd",
    surname: "Lull",
      lightTrails: [150, 40, 60, 15, 15, 10, 10]
}, {
  "fname": "Sean",
    surname: "Marx",
      lightTrails: [180, 50, 50, 20, 20, 15, 25]
}

我发现了2个类似的问题,但其中一个是针对一系列文件,这些文件对我不起作用,而另一个则根本没有提出同样的问题。

1 个答案:

答案 0 :(得分:1)

您可以通过查找查询来实现此目的。无需使用聚合。

查询:

db.students.find({},{fname:1,surname:1,lightTrails:1,_id:0}).sort({"lightTrails.0":-1,"lightTrails.1":-1}).limit(5)

结果:

{ "fname" : "Jim", "surname" : "Jones", "lightTrails" : [ 200, 70, 30, 30, 15, 15, 40 ] }
{ "fname" : "Sean", "surname" : "Marx", "lightTrails" : [ 180, 50, 50, 20, 20, 15, 25 ] }
{ "fname" : "Todd", "surname" : "Lull", "lightTrails" : [ 150, 40, 60, 15, 15, 10, 10 ] }
{ "fname" : "Flynn", "surname" : "Moore", "lightTrails" : [ 100, 40, 25, 15, 5, 10, 5 ] }
{ "fname" : "Al", "surname" : "Ryan", "lightTrails" : [ 80, 20, 20, 10, 10, 10, 10 ] }