哪一個 MongoDB 查詢在陣列中多次找到相同的值?


您可以使用 $where 運算子和一些指令碼。

我們先用文件建立集合 −

> 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")
}

以下是使用 find() 方法從集合中顯示所有文件的查詢 −

> dbsameValueMultipleTimesDemofind()pretty();

輸出

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

以下是查詢陣列中相同值多次出現的查詢 −

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

輸出

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

更新於: 30-Jul-2019

96 次瀏覽

開啟您的 職業生涯

完成該課程並獲得認證

開始
廣告