Pymongo tutorial (2) aggregate operations

Source: Internet
Author: User
Common aggregation operations in MongoDB include aggregation, mapreduce, and group. First, add some test data: db. things. insert ({x: 1, tags: [dog, cat]}) db. things. insert ({x: 2, tags: [cat]}) db. things. insert ({x: 2, tags: [mouse, cat, dog]})

Common aggregation operations in MongoDB include aggregation, map/reduce, and group. First, add some test data: db. things. insert ({"x": 1, "tags": ["dog", "cat"]}) db. things. insert ({"x": 2, "tags": ["cat"]}) db. things. insert ({"x": 2, "tags": ["mouse", "cat", "dog"]})

Common aggregation operations in MongoDB include aggregation, map/reduce, and group.

First, add some test data:

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

The following example shows how many times each value in the tags field appears.

from bson.son import SONdb.things.aggregate([    {"$unwind": "$tags"},    {"$group": {"_id": "$tags", "count": {"$sum": 1}}},    {"$sort": SON([("count", -1), ("_id", -1)])}]){'ok': 1.0, 'result': [{'count': 3, '_id': 'cat'}, {'count': 2, '_id': 'dog'}, {'count': 1, '_id': 'mouse'}]}

Note: The aggregate operation requires that the server program version 2.1.0 or later be used. The PyMongo driver is later than 2.3.

Map/Reduce

The preceding operations can also be completed using Map/Reduce.

from bson.code import Codemapper = Code("""    function () {      this.tags.forEach(function(z) {        emit(z, 1);      });    }""")reducer = Code("""    function (key, values) {      var total = 0;      for (var i = 0; i < values.length; i++) {        total += values[i];      }      return total;    }""")result = db.things.map_reduce(mapper, reducer, "myresults")for doc in result.find():    print(doc){u'_id': u'cat', u'value': 3.0}{u'_id': u'dog', u'value': 2.0}{u'_id': u'mouse', u'value': 1.0}

Map and reduce are both javascript Functions. The map_reduce method saves the statistical results to a temporary dataset.

Group

The group operation is similar to the SQL GROUP BY operation and easier than Map/Reduce operation.

reducer = Code("""    function(obj, prev){      prev.count++;    }""")results = db.things.group(key={"x":1}, condition={}, initial={"count": 0}, reduce=reducer)for doc in results:    print(doc){'x': 1.0, 'count': 1.0}{'x': 2.0, 'count': 2.0}{'x': 3.0, 'count': 1.0}

Note: The group operation is not supported in the MongoDB cluster environment. You can use aggregation or map/reduce instead.

Complete MongoDB aggregation documentation: http://docs.mongodb.org/manual/aggregation/

Original article address: pymongo tutorial (2) -- aggregate operation. Thank you for sharing it with the original author.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.