Difference between revisions of "Sum and Count"
From NoSQLZoo
m |
m |
||
(3 intermediate revisions by the same user not shown) | |||
Line 7: | Line 7: | ||
</div> | </div> | ||
<div class="q nonum" data-lang="mongo"><code>.count()</code> | <div class="q nonum" data-lang="mongo"><code>.count()</code> | ||
− | <pre class="def">db.world.count({"continent":"Africa"})</pre> | + | <pre class="def"><nowiki>db.world.count({"continent": "Africa"});</nowiki></pre> |
</div> | </div> | ||
<div class="q nonum" data-lang="mongo"><code>$sum</code> | <div class="q nonum" data-lang="mongo"><code>$sum</code> | ||
− | <pre class="def"> | + | <pre class="def"><nowiki> |
db.world.aggregate([ | db.world.aggregate([ | ||
− | {"$group":{ | + | {"$group": { |
"_id": "$continent", | "_id": "$continent", | ||
"sum of populations": {$sum: "$population"}, | "sum of populations": {$sum: "$population"}, | ||
"count of countries": {$sum: 1} | "count of countries": {$sum: 1} | ||
}} | }} | ||
− | ]) | + | ]);</nowiki></pre> |
− | </pre> | ||
</div> | </div> | ||
<div class="q nonum" data-lang="mongo"><code>Array.sum()</code> | <div class="q nonum" data-lang="mongo"><code>Array.sum()</code> | ||
− | <pre class="def"> | + | <pre class="def"><nowiki> |
db.world.mapReduce( | db.world.mapReduce( | ||
− | function(){ | + | function () { |
emit(this.continent, this.population); | emit(this.continent, this.population); | ||
}, | }, | ||
− | function(k,v){ | + | function (k, v) { |
return Array.sum(v); | return Array.sum(v); | ||
}, | }, | ||
{ | { | ||
− | out:{inline:1} | + | out: {inline: 1} |
} | } | ||
− | ) | + | ); |
− | </pre> | + | </nowiki></pre> |
</div> | </div> |
Latest revision as of 16:41, 18 July 2018
There are many ways to do this in MongoDB.
count()
is a cursor method that takes a query and returns a number equal to the amount of documents that matched the query.
$sum
is an aggregation operator availible in the $group
stage, that can be used to both sum values and count the number of documents.
mapReduce
can produce a sum or a count during the results stage by using JavaScript.
.count()
db.world.count({"continent": "Africa"});
$sum
db.world.aggregate([ {"$group": { "_id": "$continent", "sum of populations": {$sum: "$population"}, "count of countries": {$sum: 1} }} ]);
Array.sum()
db.world.mapReduce( function () { emit(this.continent, this.population); }, function (k, v) { return Array.sum(v); }, { out: {inline: 1} } );