MongoDB: записать результат агрегации в новую коллекцию

MongoDB: записать результат агрегации в новую коллекцию

В этой статье показано 2 способа экспорта результата «агрегации» MongoDB в другую новую коллекцию.

1. $out Example

Этот оператор$out появился в версии 2.6.

1.1 Review a simple grouping example, it writes the result to a new variable “result”.

> var result = db.hc_hosting.aggregate(
    {
        $group : {
            _id : "$hosting",
            total : { $sum : 1 }
        }
    }
);

1.2 Same example, but use $out operator to export the result into a new collection hc_hosting_stat.

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

2. Пример классической вставки

Это классический способ экспортировать результат в новую коллекцию.

2.1 Assigns the result to a “result” variable.

> var result = db.hc_hosting.aggregate(
    {
        $group : {
            _id : "$hosting",
            total : { $sum : 1 }
        }
    }
);

2.1 List of the available methods in the “result” variable. toArray() - это то, что вам нужно.

> result.help()

Cursor methods
    .toArray() - iterates through docs and returns an array of the results
    .forEach( func )
    .map( func )
    .hasNext()
    .next()
    .objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)
    .itcount() - iterates through documents and counts them
    .pretty() - pretty print each document, possibly over multiple lines

2.3 Insert the result like the following :

> db.hc_hosting_sum.insert(result.toArray());

Полный пример для вставки совокупного результата в новую коллекцию.

> var result = db.hc_hosting.aggregate(
    {
        $group : {
            _id : "$hosting",
            total : { $sum : 1 }
        }
    }
);

> db.hc_hosting_sum.insert(result.toArray());