按多个字段分组值

时间:2018-06-19 16:40:09

标签: mongodb aggregation-framework aggregation

我有这些文件:

{
  "Sigle_1": "BIOS",
  "Sigle_2": "BFTA"
},
{
  "Sigle_1": "BERP",
  "Sigle_2": "BEST"
},
{
  "Sigle_1": "BHDL",
  "Sigle_2": "BIOS"
},
{
  "Sigle_1": "BIPM",
  "Sigle_2": "BEST"
},
{
  "Sigle_1": "BHDL",
  "Sigle_2": "BIOS"
}

我如何发出将Sigle_1和Sigle_2串联在一起的请求,并且组值重新计算?

预期结果示例:

{
  "Sigle": "BIOS",
},
{
  "Sigle": "BFTA",
},
{
  "Sigle": "BERP",
},
{
  "Sigle": "BEST",
},
{
  "Sigle": "BHDL",
},
{
  "Sigle": "BIPM",
}

我尝试过了,但是还不完整

db.users.aggregate([{$group: {_id: {Sigle1: '$Sigle_1', Sigle2: '$Sigle_2'}}}])

2 个答案:

答案 0 :(得分:2)

您需要在此处使用$facet$group分离Sigle_1Sigle_2,然后$concatArrays合并两个数组,最后合并$group区分整个数据

db.collection.aggregate([
  { "$facet": {
    "array1": [
      { "$group": {
        "_id": "$Sigle_1"
      }}
    ],
    "array2": [
      { "$group": {
        "_id": "$Sigle_2"
      }}
    ]
  }},
  { "$addFields": {
    "data": {
      "$concatArrays": ["$array1", "$array2"]
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" }},
  { "$group": {
    "_id": "$_id"
  }},
  { "$project": { "Sigle": "$_id", "_id": 0 }}
])

输出

[
  {
    "Sigle": "BFTA"
  },
  {
    "Sigle": "BEST"
  },
  {
    "Sigle": "BHDL"
  },
  {
    "Sigle": "BERP"
  },
  {
    "Sigle": "BIPM"
  },
  {
    "Sigle": "BIOS"
  }
]

您选中了here

答案 1 :(得分:0)

我可以在单个查询中添加另一个字段!!!

{
  "Sigle_1": "BIOS",
  "Sigle_2": "BFTA",
  "Name_1": "Basic Input Output System",
  "Name_2": "Belgian Food Truck Association"

},
{
  "Sigle_1": "BERP",
  "Sigle_2": "BEST",
  "Name_1": "British Experimental Rotor Programme",
  "Name_2": "Board of European Students of Technology"
},
{
  "Sigle_1": "BHDL",
  "Sigle_2": "BIOS",
  "Name_1": "B Hardware Description Language",
  "Name_2": "Basic Input Output System"
},
{
  "Sigle_1": "BIPM",
  "Sigle_2": "BEST",
  "Name_1": "Brevet d'initiation au parachutisme militaire",
  "Name_2": "Board of European Students of Technology"
},
{
  "Sigle_1": "BHDL",
  "Sigle_2": "BIOS",
  "Name_1": "B Hardware Description Language",
  "Name_2": "Basic Input Output System"
}