abbensid
abbensid

Reputation: 45

group values by multiple fields

I have these documents:

{
  "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"
}

How can I make a request, which will concatenate Sigle_1 and Sigle_2 And group values reslut?

Example of expected result:

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

I tried this but it's not complete

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

Upvotes: 2

Views: 728

Answers (2)

abbensid
abbensid

Reputation: 45

I can add another field in a single query !!!

{
  "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"
}

Upvotes: 0

Ashh
Ashh

Reputation: 46491

You need to use $facet here to $group separate Sigle_1 and Sigle_2 and then $concatArrays to merge both arrays and then finally $group to distinct the whole data

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 }}
])

Output

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

You check it here

Upvotes: 2

Related Questions