MongoDB Query to Find Same Value Multiple Times in an Array



You can use $where operator along with some script.

Let us first create a collection with documents −

> dbsameValueMultipleTimesDemoinsertOne(
   {
      "ListOfPrice":[
         {"Price": 110},
         {"Price":130},
         {"Price": 145}
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefc4e6ef71edecf6a1f6b9")
}
> dbsameValueMultipleTimesDemoinsertOne(
   {
      "ListOfPrice":[
         {"Price": 110},
         {"Price":178},
         {"Price": 110}
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefc4e7ef71edecf6a1f6ba")
}

Following is the query to display all documents from a collection with the help of find() method −

> dbsameValueMultipleTimesDemofind()pretty();

Output

{
   "_id" : ObjectId("5cefc4e6ef71edecf6a1f6b9"),
   "ListOfPrice" : [
      {
         "Price" : 110
      },
      {
         "Price" : 130
      },
      {
         "Price" : 145
      }
   ]
}
{
   "_id" : ObjectId("5cefc4e7ef71edecf6a1f6ba"),
   "ListOfPrice" : [
      {
         "Price" : 110
      },
      {
         "Price" : 178
      },
      {
         "Price" : 110
      }
   ]
}

Following is the query to find same value multiple times in an array −

> dbsameValueMultipleTimesDemofind({
   "$where": function() {
      return thisListOfPricefilter(function(p) {
         return pPrice == 110;
      })length > 1;
   }
})

Output

{ "_id" : ObjectId("5cefc4e7ef71edecf6a1f6ba"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 178 }, { "Price" : 110 } ] }
Updated on: 2019-07-30T22:30:26+05:30

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements