One MongoDB statistic requirement

Source: Internet
Author: User

Demand:

A colleague from the off-duty operation sent a requirement to count the number of occurrences of a field (_ID) in all document in a collection in the database. The range of the _id field is 0-4000.

Suppose collection is like this:

{    123},{    456},{    _id:123}

So the end result: [{_id:123, value:2}, {_id:456, value:1}] is actually a count frequency operation

Scheme:

Rough methods can traverse all document and accumulate, but the better way is to use MongoDB's MapReduce operation: https://docs.mongodb.com/manual/core/map-reduce/

db.collection.mapReduce (    function() {Emit (this. _id, 1)},      function(key, values) {return  array.sum (values);},    1}}    )

It is worth mentioning that emit, value is 1, so that each document is a 1, then reduce when we get a full 1 array.

Next, using the method mentioned by http://www.cnblogs.com/agentgamer/p/4994650.html, can be inherited into the shell, the standard output to other tools to use, the output of the inline is basically a JSON.

One MongoDB statistic requirement

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.