从数组mongodb中查找前3个值

时间:2019-05-21 16:21:25

标签: node.js mongodb mongodb-query aggregation-framework

我在以下集合中有一组对象,这些对象具有我想要的级别 数组中只有前3个级别按级别降序排列

{
    "_id" : ObjectId("5ce10ffb0a9531d98ad11819"),
    "_course" : ObjectId("593107b273790c30c4e08b02"),
    "users" : [ 
        {
            "level" : 17,
            "_user" : ObjectId("5c08be10d1a0c91e4c739629")
        }, 
        {
            "level" : 16,
            "_user" : ObjectId("593107b273790c30c4e08b07")
        },
        {
            "level" : 5,
            "_user" : ObjectId("593107b273790c30c4e08b08")
        },
        {
            "level" : 17,
            "_user" : ObjectId("593107b273790c30c4e08b05")
        }
    ],
    "acr" : "MH"
}

/* 2 */
{
    "_id" : ObjectId("5ce10ffb0a9531d98ad1181a"),
    "_course" : ObjectId("593107b273790c30c4e08b02"),
    "users" : [ 
        {
            "level" : 9,
            "_user" : ObjectId("5c08be10d1a0c91e4c739629")
        }, 
        {
            "level" : 6,
            "_user" : ObjectId("593107b273790c30c4e08b02")
        },
        {
            "level" : 5,
            "_user" : ObjectId("593107b273790c30c4e08b07")
        },
        {
            "level" : 4,
            "_user" : ObjectId("593107b273790c30c4e08b07")
        }
    ],
    "acr" : "MA"
}

预期产量

  {
    "_id": "5ce10ffb0a9531d98ad11819",
    "users": [
      {
        "level": 17,
        "_user": "593107b273790c30c4e08b09"
      },
      {
        "level": 17,
        "_user": "593107b273790c30c4e08b05"
      },
      {
        "level": 16,
        "_user": "593107b273790c30c4e08b07"
      }
    ]
  },
  {
    "_id": "5ce10ffb0a9531d98ad11819",
    "users": [
      {
        "level": 9,
        "_user": "593107b273790c30c4e08b09"
      },
      {
        "level": 6,
        "_user": "593107b273790c30c4e08b02"
      },
      {
        "level": 5,
        "_user": "593107b273790c30c4e08b07"
      }
    ]
  }

我想要像上面一样的预期输出,我正在使用聚合,但是我找不到办法。我也使用其他方式,但仍然无法获得正确的输出,我找不到

1 个答案:

答案 0 :(得分:4)

您可以使用以下汇总

db.collection.aggregate([
  { "$unwind": "$users" },
  { "$sort": { "users.level": -1 }},
  { "$group": {
    "_id": "$_id",
    "users": { "$push": "$users" }
  }},
  { "$addFields": { "users": { "$slice": ["$users", 3] }}}
])

MongoPlayground