如何使用 MongoDB 查找值顺序不同的精确数组匹配项?
要找到顺序不同的值的精确数组匹配项,可以使用 $all 运算符。让我们创建一个包含文档的集合。以下是查询
>db.exactMatchArrayDemo.insertOne({"StudentName":"David","StudentAge":22,"StudentGameScores":[45,78,98]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c94702d6669774125246c")
}
>db.exactMatchArrayDemo.insertOne({"StudentName":"Chris","StudentAge":23,"StudentGameScores":[45,78]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c94a42d6669774125246d")
}以下是要借助 find() 方法从集合中显示所有文档的查询
> db.exactMatchArrayDemo.find().pretty();
这将会生成以下输出
{
"_id" : ObjectId("5c9c94702d6669774125246c"),
"StudentName" : "David",
"StudentAge" : 22,
"StudentGameScores" : [
45,
78,
98
]
}
{
"_id" : ObjectId("5c9c94a42d6669774125246d"),
"StudentName" : "Chris",
"StudentAge" : 23,
"StudentGameScores" : [
45,
78
]
}以下是要查找精确数组匹配项的查询
> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 2, "$all": [ 78, 45 ] } }).pretty();这将会生成以下输出
{
"_id" : ObjectId("5c9c94a42d6669774125246d"),
"StudentName" : "Chris",
"StudentAge" : 23,
"StudentGameScores" : [
45,
78
]
}以下是要查找精确数组匹配项但顺序无关紧要的查询。我们已设置不同的大小,以便使用 3 个值获取字段“StudentGameScores”
> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 3, "$all": [ 78, 45 ] } }).pretty();这将会生成以下输出
{
"_id" : ObjectId("5c9c94702d6669774125246c"),
"StudentName" : "David",
"StudentAge" : 22,
"StudentGameScores" : [
45,
78,
98
]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP