Which MongoDB query finds 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: 30-Jul-2019

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements