3

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?

2
  • followers and following would be the Array. right? Commented Nov 29, 2018 at 11:31
  • @HardikShah yes! Commented Nov 29, 2018 at 11:32

1 Answer 1

2

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you but How I can query within a single document( I want to find duplicate ids in a single document but in two different fields)
Yes, you can with the same snippet I have provided. Just to add $match to specific Id at the top level of aggregation. Can you post your whole sample data struct? So, I can modify with your requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.