MongoDB组并按键排序

时间:2019-04-02 10:36:40

标签: mongodb

我有一个mongodb集合,其中包含以下数据:

{
    "_id" : "100",
    "deleted" : false,
    "alphanumericKey" : "s",
    "sortName" : "stackoverflow",
     "name" : [ 
        {
            "value" : "Stack Overflow",
            "language" : "en"
        }
    ]
}
{
    "_id" : "101",
    "deleted" : false,
    "alphanumericKey" : "s",
    "sortName" : "something",
     "name" : [ 
        {
            "value" : "Something else with s",
            "language" : "en"
        }
    ]
}
{
    "_id" : "103",
    "deleted" : false,
    "alphanumericKey" : "x",
    "sortName" : "xerox",
     "name" : [ 
        {
            "value" : "Xerox",
            "language" : "en"
        }
    ]
}

现在,我需要运行一个查询,该查询将按每个项目的字母数字值对结果进行分组,并在此新键下显示整个对象。如果按字母顺序对它们进行排序也不会造成伤害,但这真是太好了……无论如何,最终看起来像这样:

{
  "s": [{
      "_id": "101",
      "deleted": false,
      "alphanumericKey": "s",
      "sortName": "something",
      "name": [{
        "value": "Something else with s",
        "language": "en"
      }]
    },
    {
      "_id": "100",
      "deleted": false,
      "alphanumericKey": "s",
      "sortName": "stackoverflow",
      "name": [{
        "value": "Stack Overflow",
        "language": "en"
      }]
    }
  ]
}

{
  x: [{
    "_id": "103",
    "deleted": false,
    "alphanumericKey": "x",
    "sortName": "xerox",
    "name": [{
      "value": "Xerox",
      "language": "en"
    }]
  }]
}

1 个答案:

答案 0 :(得分:1)

技巧是使用$$ ROOT进行$ group阶段。答案是:

aws s3api delete-objects --bucket mybucket --delete 'Objects=[{Key=2019-03-27T160001Z.tar},{Key=2019-03-27T170001Z.tar}]'

会返回

db.collection.aggregate([
  {
    $group: {
      _id: "$alphanumericKey",
      docs: {
        $push: "$$ROOT"
      }
    },

  },
  {
    $sort: {
      _id: 1
    }
  }
])

编辑:对于不能使用$$ ROOT的用户(在2.6之前),您需要在$ group累加器阶段描述整个文档,例如:

[
  {
    "_id": "s",
    "docs": [
      {
        "_id": "100",
        "alphanumericKey": "s",
        "deleted": false,
        "name": [
          {
            "language": "en",
            "value": "Stack Overflow"
          }
        ],
        "sortName": "stackoverflow"
      },
      {
        "_id": "101",
        "alphanumericKey": "s",
        "deleted": false,
        "name": [
          {
            "language": "en",
            "value": "Something else with s"
          }
        ],
        "sortName": "something"
      }
    ]
  },
  {
    "_id": "x",
    "docs": [
      {
        "_id": "103",
        "alphanumericKey": "x",
        "deleted": false,
        "name": [
          {
            "language": "en",
            "value": "Xerox"
          }
        ],
        "sortName": "xerox"
      }
    ]
  }
]