Sum and Count: Difference between revisions
From NoSQLZoo
No edit summary |
No edit summary |
||
| Line 42: | Line 42: | ||
<div class=q data-lang="py3">Array.sum() | <div class=q data-lang="py3">Array.sum() | ||
<div class="def">temp = db.world.map_reduce( | <div class="def">temp = db.world.map_reduce( | ||
map=Code("function(){emit(this. | map=Code("function(){emit(this.continent, this.population)}"), | ||
reduce=Code("""function(k,v){ | reduce=Code("""function(k,v){ | ||
return Array.sum(v) | return Array.sum(v) | ||
Revision as of 09:23, 28 July 2015
#ENCODING
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-16')
#MONGO
from pymongo import MongoClient
client = MongoClient()
client.progzoo.authenticate('scott','tiger')
db = client['progzoo']
#PRETTY
import pprint
pp = pprint.PrettyPrinter(indent=4)
#CODE
from bson.code import Code
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()
print(db.world.count({"continent":"Africa"}))
$sum
pp.pprint(list(
db.world.aggregate([
{"$group":{
"_id":"$continent",
"sum of populations":{"$sum":"$population"},
"count of countries":{"$sum":1}
}}
])
))
Array.sum()
temp = db.world.map_reduce(
map=Code("function(){emit(this.continent, this.population)}"),
reduce=Code("""function(k,v){
return Array.sum(v)
}
"""),
out={"inline":1}
)
pp.pprint(temp['results'])