MongoDB按嵌套数组排序

时间:2014-04-30 01:52:42

标签: mongodb sorting mapreduce aggregation-framework

我现在正在使用mongodb来获得我想要的东西。

{
  "_id" : ObjectId("533b66f3e4b038c01f6a427f"),
  "ccNameCount" : [{
      "ccName" : "ATCC",
      "paperCount" : 4660,
      "strainCount" : 9339,
      "version" : 1
    }, {
      "ccName" : "BCC",
      "paperCount" : 24,
      "strainCount" : 41
    }, {
      "ccName" : "BCCM/DCG",
      "paperCount" : 3,
      "strainCount" : 7
    }]
}

示例文档就像这样。现在,我想查询ccNameCount.ccName = ATCC的文档,并通过cource的paperCount.But对结果进行排序,因为ccNameCount是一个数组,只需按键ccNameCount排序就不会给出我想要的是什么。所以,我的问题是,我该怎么办?使用MapReduce?

1 个答案:

答案 0 :(得分:3)

您最好的选择是aggregation framework

db.collection.aggregate([

    // Match the "documents" that contain your condition
    // reduces the working size
    { "$match": {
        "ccNameCount.ccName": "ATCC"
    }},

    // Keep the original document, you might not really care about this
    { "$project": {
        "_id": {
            "_id": "$_id",
            "ccNameCount": "$ccNameCount"
        },
        "ccNameCount": 1
   }},

    // Unwind the array to de-normalize
    { "$unwind": "$ccNameCount" },

    // Now just match those elements (now documents) as your condition
    { "$match": {
        "ccNameCount.ccName": "ATCC"
    }},

    // Sort the results on the now selected "paperCount"
    { "$sort": { "ccNameCount.paperCount": -1 } },

    // Put the documents back to normal if you want
    { "$project": {
        "_id": "$_id._id",
        "ccNameCount": "$_id.ccNameCount"
    }}

])

所以在此之后实际上"选择"您的匹配数组元素,然后可以按此位置的字段对结果进行排序。如果您希望在结果中返回数组的原始状态,则 $project 阶段是可选的,否则阶段仅选择匹配的条目并对其进行正确排序