0
votes

In my mongo db collection , I have few documents as below : Each Document has a 'Bricks' array .

  • In the Bricks Array , some documents have same 'brick_id' ( see - Document 1)
  • Some documents have unique 'brick_id' ( see - Document 2)

Now, My Question is that I need to write a Mongo Query to retrieve all the Documents which contains redundant 'brick_id' in the "bricks" array .

Means , I need to get Document 1 as output

Please help . I'm new to Mongo Db

**Document 1** :
{
  "_id" : 123 ,
  "page" : "new_page_1" ,
   "bricks" : [
      {
         "brick_id" : 160,
         "name" : "dev-br" 
      },
      {
          "brick_id" : 160,
          "name" : "dev-br2" 
      }
   ]
}

**Document 2**

{
  "_id" : 150 ,
  "page" : "new_page_1" ,
   "bricks" : [
      {
         "brick_id" : 200,
         "name" : "dev-br" 
      },
      {
          "brick_id" : 201,
          "name" : "dev-br2" 
      }
   ]
}

1

1 Answers

0
votes

You might use the $setUnion operator to join "$bricks.brick_id" with an empty array, and compare its $size with that of the unmodified "$bricks.brick_id" array. If the sizes are not equal, there was at least one duplicate.