Omid
Omid

Reputation: 113

How to find duplicate values in different object fields?

How can I search with mongoose to find duplicate values in different fields?


Here is sample document:

{
 "followers": {
               {
                "_id": "5bf6d610d3a3f31a6c75a9f4"
               },
               {
                "_id": "5bf6d610d3a3f31a6c75a8c3"
               }
              },
 "following": {
               {
                "_id": "5bf6d610d3a3f31a6c75a9f4"
               },
               {
                "_id": "5bf6d610d3a3f31a6c75b7a2"
               }
              },
}

I want to find same _id values under followers and following fields.

Expected Output:

{
 {
  "_id": "5bf6d610d3a3f31a6c75a9f4"
 }
}

What query should I use?

Upvotes: 3

Views: 68

Answers (1)

Hardik Shah
Hardik Shah

Reputation: 4200

Try with this:

db.collection.aggregate([
    { $unwind : "$followers"},
    { $unwind : "$following"},
    { $project : {
        _id: 0,
        matchId: { $cond: [ {$eq: [ "$followers._id", "$following._id" ]} ,
          "$following._id", null ] }
    }},
    {$match : {"matchId" : {$ne : null}}}
])

Output:

/* 1 */
{
    "matchId" : "5bf6d610d3a3f31a6c75a9f4"
}

Upvotes: 2

Related Questions