Cookies help us deliver our services. By using our services, you agree to our use of cookies. More information

Difference between revisions of "Sum and Count"

From NoSQLZoo
Jump to: navigation, search
(Created page with "<pre class=setup> #ENCODING import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-16') #MONGO from pymongo import MongoClient client = MongoClien...")
 
Line 17: Line 17:
 
{{TopTenTips}}
 
{{TopTenTips}}
 
<div style="height:25em">
 
<div style="height:25em">
 +
There are many ways to do this in MongoDB.<br/><br/>
 +
<code>count()</code> is a cursor method that takes a query and returns a number equal to the amount of documents that matched the query.<br/>
 +
<code>$sum</code> is an aggregation operator availible in the <code>$group</code> stage, that can be used to both sum values and count the number of documents.<br/>
 +
mapReduce can produce a sum or a count during the results stage.
 +
</div>
 +
<div class=q data-lang="py3">.count()
 +
<div class="def">
 +
print(db.world.count("continent":"Africa"))
 +
</div>
 +
</div>
  
 +
<div class=q data-lang="py3">$sum
 +
<div class="def">
 +
pp.pprint(list(
 +
    db.world.aggregate([
 +
        {"$group":{
 +
            "_id":"$continent",
 +
            "sum of population":{"$sum":"$population"},
 +
            "count of countries":{"$sum":1}
 +
        }}
 +
    ])
 +
))
 
</div>
 
</div>
<div class=q data-lang="py3">
+
</div>
 +
 
 +
<div class=q data-lang="py3">.count()
 
<div class="def">
 
<div class="def">
 +
print(db.world.count("continent":"Africa"))
 
</div>
 
</div>
 
</div>
 
</div>

Revision as of 15:04, 27 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.

.count()

print(db.world.count("continent":"Africa"))

$sum

pp.pprint(list(

   db.world.aggregate([
       {"$group":{
           "_id":"$continent",
           "sum of population":{"$sum":"$population"},
           "count of countries":{"$sum":1}
       }}
   ])

))

.count()

print(db.world.count("continent":"Africa"))