MongoDB Group data different fields distinct problem solving method

Source: Internet
Author: User
Tags ip number prev

Recently by the aggregation of MongoDB baffled, conditions:

1, the table has the field Mac,pv,ip,dates,type

2, requirements, based on IP to group, calculate PV Total, non-duplicated Mac number, non-duplicated IP number

3, the following is the solution, Description: MongoDB authoritative guide is used in the object, that is, "Macs": {}, and then in the reduce with in to find, prev.macs[obj.mac]= "" To add, easy to appear unexpected number error

Now it's easy to change the array and clear it in finalize

1 Db.test.group ({2"Key": "IP",3"Initial": {"Mac": 0, "PV": 0, "IP": 0, "Macs": [], "IPs":[]},4"$reduce":function(Obj,prev) {5         if(Prev.macs.indexOf (OBJ.MAC) <0){6Prev.mac =Prev.macs.push (OBJ.MAC);7         }8         if(Prev.ips.indexOf (OBJ.IP) <0){9Prev.ip =Prev.ips.push (OBJ.IP);Ten         } Oneprev.pv+=OBJ.PV; A     }, -"Finalize":function(prev) { -prev.macs=[]; theprev.ips=[]; -     }, -"condition": {"dates": "2014-05-09", "type": "Type1"} -});

If there is a better way, please leave a message and discuss together

Related Article

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.