ML
    • Recent
    • Categories
    • Tags
    • Popular
    • Users
    • Groups
    • Register
    • Login

    Find Duplicate Value Entries in MongoDB Collection

    IT Discussion
    mongodb nosql javascript aggregate
    1
    2
    6.4k
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • scottalanmillerS
      scottalanmiller
      last edited by

      Without access to SQL, sometimes simple queries can be confusing in NoSQL systems. If we want to do a simple search in MongoDB to find duplicate values in a collection, it can be a little confusing.

      In my example, we go through the "myCollection" collection and look for values in "field_to_search" that are duplicated at least once and list them. You need only change "myCollection" to the name of your collection and "field_to_search" to the name of the field that you want to check for duplicates and voila.

      db.myCollection.aggregate([ {$group: { _id: "$field_to_search", count: { $sum: 1}}}, {$match: { count: { $gt: 1 }}}])
      
      1 Reply Last reply Reply Quote 3
      • scottalanmillerS
        scottalanmiller
        last edited by

        For more detail, showing the UIDs of each of the duplicates in question, try this little extension:

        db.myCollection.aggregate([ {$group: { _id: "$field_to_search", "dups": { "$push": "$_id" }, count: { $sum: 1}}}, {$match: { count: { $gt: 1 }}}])
        
        1 Reply Last reply Reply Quote 1
        • 1 / 1
        • First post
          Last post