Exemple #1
0
db = client().demo

db.animals.insert({"x": 1, "tags": ["dog", "cat"]})
db.animals.insert({"x": 2, "tags": ["cat"]})
db.animals.insert({"x": 3, "tags": ["mouse", "cat", "dog"]})
db.animals.insert({"x": 4, "tags": []})

db.animals.aggregate([{
    "$unwind": "$tags"
}, {
    "$group": {
        "_id": "$tags",
        "count": {
            "$sum": 1
        }
    }
}, {
    "$sort": son([("count", -1), ("_id", -1)])
}])
'''
result:
{u'ok': 1.0,
 u'result':
        [
            {u'_id': u'cat', u'count': 3},
            {u'_id': u'dog', u'count': 2},
            {u'_id': u'mouse', u'count': 1}
        ]
}
'''
Exemple #2
0
                return total;
            }
            """)


db = client().demo
result = db.animals.map_reduce(mapper, reducer, "myresults")

for doc in result.find():
    print doc


# get more detailed results when desired, by passing full_response=True to map_reduce()
result = db.animals.map_reduce(mapper, reducer, "myresults", full_response=True)

# all of the optional map/reduce parameters are also supported, simply pass them as keyword arguments
result = db.animals.map_reduce(mapper, reducer, "myresults", query={"x": {"$gt": 2}})

# can use SON or collections.OrderedDict to specify a different database to store the result collection
result = db.animals.map_reduce(mapper, reducer, out=son([("replace", "results"), ("db", "outdb")]), full_response=True)

# group() method provides some of the same functionality as SQL’s GROUP BY.
# Simpler than a map reduce you need to provide a key to group by, an initial value for the aggregation and a reduce function.
# group() doesn't work with sharded mongodb configurations.
reducer = code("""
            function(obj, prev) {
                prev.count++;
            }
            """)
result = db.animals.group(key={"x": 1}, condition={}, initial={"count": 0}, reduce=reducer)
Exemple #3
0

# because of python dictionaries don't maintain order,
# you should use son or collections.OrderedDict
# where explicit ordering is required e.g. "$sort"
from bson.son import SON as son
from pymongo import MongoClient as client

db = client().demo

db.animals.insert({"x": 1, "tags": ["dog", "cat"]})
db.animals.insert({"x": 2, "tags": ["cat"]})
db.animals.insert({"x": 3, "tags": ["mouse", "cat", "dog"]})
db.animals.insert({"x": 4, "tags": []})

db.animals.aggregate([{"$unwind": "$tags"},
                   {"$group": {"_id": "$tags", "count": {"$sum": 1}}},
                   {"$sort": son([("count", -1), ("_id", -1)])}])

'''
result:
{u'ok': 1.0,
 u'result':
        [
            {u'_id': u'cat', u'count': 3},
            {u'_id': u'dog', u'count': 2},
            {u'_id': u'mouse', u'count': 1}
        ]
}
'''