如何使用 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