MongoDB Delete duplicate data

Source: Internet
Author: User

Insert six data:

The query has duplicate data:
Query and iterate delete duplicate data: Delete statement resolution: Db.userInfo.aggregate ([{$group: {_id: {userName: ' $userName ',Age : ' $age '},Count: {$sum: 1},dups: {$addToSet: ' $_id '}}}, {$match: {Count: {$GT: 1}}}]). ForEach (function (doc) {doc.dups.shift (); Db.userInfo.remove ({_id: {$in: Doc.dups}});}) 1. Based on the username and age groupings and statistics, $group returns only the fields participating in the grouping, using $addtoset to add _id field 2 to the returned result array. Use $match to match data 3 with a quantity greater than 1.doc.dups.shift (); means to delete from the first value of the array; The function is to kick apart one of the _id, so that the subsequent DELETE statement does not delete all the data4. Using the Foreach loop to delete data based on _id $addToSet operator adds a value to the array only if the value does not exist in the array. If the value already exists in the array, $addToSet returns and does not modify the array. Reference Address: http://forum.foxera.com/mongodb/topic/967/mongodb%E5%A6%82%E4%BD%95%E5%B0%86%E9%87%8D%E5%A4%8D%E7%9A%84% E6%95%b0%e6%8d%ae%e5%88%a0%e9%99%a4

MongoDB Delete duplicate data

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.