如何在 MongoDB 中透過整數陣列搜尋文件?
對此,您可以使用 $where 運算子。我們首先使用文件建立一個集合 -
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"John","StudentScores":[45,78,89,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a219345990cee87fd88c")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Larry","StudentScores":[45,43,34,33]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a22a345990cee87fd88d")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Chris","StudentScores":[]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a23c345990cee87fd88e")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"David","StudentScores":[99]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a24d345990cee87fd88f")
}以下是對集合中所有文件顯示查詢,採用 find() 方法 -
> db.searchDocumentArrayIntegerDemo.find().pretty();
將會產生以下輸出 -
{
"_id" : ObjectId("5cd2a219345990cee87fd88c"),
"StudentFirstName" : "John",
"StudentScores" : [
45,
78,
89,
90
]
}
{
"_id" : ObjectId("5cd2a22a345990cee87fd88d"),
"StudentFirstName" : "Larry",
"StudentScores" : [
45,
43,
34,
33
]
}
{
"_id" : ObjectId("5cd2a23c345990cee87fd88e"),
"StudentFirstName" : "Chris",
"StudentScores" : [ ]
}
{
"_id" : ObjectId("5cd2a24d345990cee87fd88f"),
"StudentFirstName" : "David",
"StudentScores" : [
99
]
}情況 1 - 陣列中包含至少一個值時的查詢 -
> db.searchDocumentArrayIntegerDemo.find({ $where: "this.StudentScores.length >= 1" } );將會產生以下輸出 -
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentFirstName" : "John", "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentFirstName" : "Larry", "StudentScores" : [ 45, 43, 34, 33 ] }
{ "_id" : ObjectId("5cd2a24d345990cee87fd88f"), "StudentFirstName" : "David", "StudentScores" : [ 99 ] }情況 2 - 陣列中包含所有文件中的一個通用值時的查詢 -
> db.searchDocumentArrayIntegerDemo.find({StudentScores: 45}, {StudentScores:1});將會產生以下輸出 -
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentScores" : [ 45, 43, 34, 33 ] }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP