哪一个 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