哪一個 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 } ] }
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP