RedDragon
RedDragon

Reputation: 2138

How to find documents with duplicated attributes in Mongoose?

I have the following documents stored in my MongoDB database (let's say collection products):

{
   a: "test1",
   c: "data1"
},
{
   a: "test2",
   c: "data2"
},
{
   a: "test3",
   c: "data1"
},
{
   a: "test4",
   c: "data3"
},
{
   a: "test5",
   c: "data1"
},
{
   a: "test6",
   c: "data3"
},

How can I query all documents that have attribute c duplicated (or triplicated...)? In the example data, the query should return test1, test3, test4, test5 and test6 documents.

Upvotes: 0

Views: 35

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can do this by grouping on c and then getting the groups with more than one in the group:

db.test.aggregate([
    {$group: {_id: '$c', count: {$sum: 1}, docs: {$push: '$$ROOT'}}},
    {$match: {count: {$gt: 1}}}
])

Upvotes: 1

Related Questions