top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Find duplicates in array field in MongoDB?

+2 votes
1,045 views

I get duplicates of fields and subfield using aggregation. Searching for duplicated sub field "k01.v" works fine:

db.table_0.aggregate({"$group" : { _id: "$k01.v", "count": { "$sum": 1 } } }
{"$match": {"count" : {"$gt": 1} } }
{"$project": {"k01.v" : "$_id", "_id" : 0} });

Unfortunately, this doesnt work when searching for sub field "a1.0" (field "a1" is an array):

db.table_0.aggregate({"$group" : { _id: "$a1.0", "count": { "$sum": 1 } } }
{"$match": {"count" : {"$gt": 1} } }
{"$project": {"a1.0" : "$_id", "_id" : 0} });

Any workaround ?

posted Apr 25, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

try this script :

->db.table_0.find({"$arrayElemAt:["$a1",0]});
answer Apr 26, 2016 by Shivam Kumar Pandey
0 votes

Are you trying to access the first element of array "a1"? The syntax
for that in aggregation is

{$arrayElemAt:["$a1", 0] }

answer Apr 26, 2016 by Manikandan J
Similar Questions
0 votes

We all know that mongoDB provide different type of indexing (ascending, descending, geo2D, geo2d sphere, or text), so which type of indexing considered more efficient for indexing boolean field?

+1 vote

I have the following collections,

{ 
    "_id" : ObjectId("55884eddd00431413bdd1d97"),
    "username" : "test",
    "reports":[
       "folder 1":[{
         "file1":{
           "ceratedBy":"user1"
         },

         "file2":{
           "ceratedBy":"user2"
         } 
       }],

       "folder 2":[{
         "file1":{
           "ceratedBy":"user1"
         },

         "file2":{
           "ceratedBy":"user2"
         } 

       }]
     ]}

I now want to insert into the reports.folder 1 array say "file 3":{"cerated by":"user 3"}. Appreciate any help

+1 vote

I am storing color values as an array of 3 floats and want to query for distinct colors. Is there a way to make .distinct look for distinct arrays rather than values within the arrays?

...