MongoDB - Exemple d’agrégat et de groupe

MongoDB - Exemple d'agrégat et de groupe

mongodb-group-example

Dans ce tutoriel, nous allons vous montrer comment utiliser la fonction d'agrégation MongoDB pour regrouper des documents (données).

1. Données de test

Les données au format JSON montrent le fournisseur d'hébergement pour le site Web.

website.json

{ "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" }
{ "_id" : 2, "domainName" : "test2.com", "hosting" : "aws.amazon.com"}
{ "_id" : 3, "domainName" : "test3.com", "hosting" : "aws.amazon.com" }
{ "_id" : 4, "domainName" : "test4.com", "hosting" : "hostgator.com" }
{ "_id" : 5, "domainName" : "test5.com", "hosting" : "aws.amazon.com" }
{ "_id" : 6, "domainName" : "test6.com", "hosting" : "cloud.google.com" }
{ "_id" : 7, "domainName" : "test7.com", "hosting" : "aws.amazon.com" }
{ "_id" : 8, "domainName" : "test8.com", "hosting" : "hostgator.com" }
{ "_id" : 9, "domainName" : "test9.com", "hosting" : "cloud.google.com" }
{ "_id" : 10, "domainName" : "test10.com", "hosting" : "godaddy.com" }

Importe dans une collection «site Web».

> mongoimport -d testdb -c website --file website.json
connected to: 127.0.0.1
Mon Jan 13 14:30:22.662 imported 10 objects

Note
Si la collection existe, ajoutez l'option--upsert pour remplacer les données.

> mongoimport -d testdb -c website --file website.json --upsert

2. Exemple de regroupement

Utilisedb.collection.aggregate et$group pour effectuer le regroupement de données.

2.1 L'exemple suivant regroupe par le champ «hébergement» et affiche la somme totale de chaque hébergement.

> db.website.aggregate(
    {
    $group : {_id : "$hosting", total : { $sum : 1 }}
    }
  );

Sortie

{
        "result" : [
                {
                        "_id" : "godaddy.com",
                        "total" : 1
                },
                {
                        "_id" : "cloud.google.com",
                        "total" : 2
                },
                {
                        "_id" : "aws.amazon.com",
                        "total" : 4
                },
                {
                        "_id" : "hostgator.com",
                        "total" : 3
                }
        ],
        "ok" : 1
}

Le SQL équivalent.

SELECT hosting, SUM(hosting) AS total
       FROM website
       GROUP BY hosting

2.2 Ajoutez un tri avec$sort.

>  db.website.aggregate(
     {
    $group : {_id : "$hosting", total : { $sum : 1 }}
     },
     {
    $sort : {total : -1}
     }
  );

Sortie - Affiche le «total» dans l'ordre décroissant. Pour l'ordre croissant, utilise$sort : {total : 1}.

{
        "result" : [
                {
                        "_id" : "aws.amazon.com",
                        "total" : 4
                },
                {
                        "_id" : "hostgator.com",
                        "total" : 3
                },
                {
                        "_id" : "cloud.google.com",
                        "total" : 2
                },
                {
                        "_id" : "godaddy.com",
                        "total" : 1
                }
        ],
        "ok" : 1
}

2.3 Ajouter la condition$match, regrouper par «hébergement» pour «aws.amazon.com» uniquement.

> db.website.aggregate(
    {
    $match : {hosting : "aws.amazon.com"}
    },
    {
    $group : { _id : "$hosting", total : { $sum : 1 } }
    }
  );

Sortie

{
        "result" : [
                {
                        "_id" : "aws.amazon.com",
                        "total" : 4
                }
        ],
        "ok" : 1
}

More Examples
Reportez-vous à ceMongoDB Aggregation guide officiel pour plus d'agrégation avancée et des exemples de groupe.

3. Exporte le résultat du regroupement vers CSV ou JSON

Souvent, nous devons exporter les résultats du regroupement au format csv ou JSON. Pour le résoudre, insère les résultats du groupe dans une nouvelle collection et exporte la nouvelle collection viamongoexport.

3.1 Définit les résultats du groupe dans une variable. Dans ce cas, le nom de la variable est «groupdata».

> var groupdata = db.website.aggregate(
    {
    $group : {_id : "$hosting", total : { $sum : 1 }}
    },
    {
    $sort : {total : -1}
    }
  );

3.2Insèregroupdata.toArray() dans une nouvelle collection.

> db.websitegroup.insert(groupdata.toArray());

> db.websitegroup.find().pretty()
{ "_id" : "aws.amazon.com", "total" : 4 }
{ "_id" : "hostgator.com", "total" : 3 }
{ "_id" : "cloud.google.com", "total" : 2 }
{ "_id" : "godaddy.com", "total" : 1 }
>

3.3 Exporte la collection «websitegroup» vers un fichier csv.

c:\> mongoexport -d testdb -c websitegroup -f _id,total -o group.csv --csv
connected to: 127.0.0.1
exported 4 records

group.csv

_id,total
"aws.amazon.com",4.0
"cloud.google.com",2.0
"godaddy.com",1.0
"hostgator.com",3.0

3.4 Exporte la collection «websitegroup» vers un fichier JSON.

c:\> mongoexport -d testdb -c websitegroup -o group.json
connected to: 127.0.0.1
exported 4 records

group.json

{ "_id" : "aws.amazon.com", "total" : 4 }
{ "_id" : "cloud.google.com", "total" : 2 }
{ "_id" : "godaddy.com", "total" : 1 }
{ "_id" : "hostgator.com", "total" : 3 }

4. Grande opération de tri

Changed in version 2.6 - Lire ceciMemory Restrictions
Dans MongoDB, le tri en mémoire a une limite de 100M, pour effectuer un grand tri, vous devez activer l'optionallowDiskUse pour écrire des données dans un fichier temporaire pour le tri.

Pour éviter l'erreursort exceeded memory limit, activez l'optionallowDiskUse.

db.website.aggregate(
[
    {$group : {_id : "$hosting", total : { $sum : 1 }}},
    {$sort : {total : -1}}
],
    {allowDiskUse: true}
);