獲取包含陣列中特定屬性的 MongoDB 文件
為此,可以使用 $and 和點(.)符號。我們先建立一個帶有文件的集合 -
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e08b56e25ddae1f53b62219")
}
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"Carol","StudentAge":19},{"StudentName":"Bob","StudentAge":18}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e08b58625ddae1f53b6221a")
}以下是使用 find() 方法顯示集合中所有文件的查詢 -
> db.demo2.find().pretty();
這將產生以下輸出 -
{
"_id" : ObjectId("5e08b56e25ddae1f53b62219"),
"StudentInformation" : [
{
"StudentName" : "John",
"StudentAge" : 21
},
{
"StudentName" : "Mike",
"StudentAge" : 22
}
]
}
{
"_id" : ObjectId("5e08b58625ddae1f53b6221a"),
"StudentInformation" : [
{
"StudentName" : "Carol",
"StudentAge" : 19
},
{
"StudentName" : "Bob",
"StudentAge" : 18
}
]
}以下是獲取包含陣列中特定屬性的文件的查詢 -
>db.demo2.find({$and:[{"StudentInformation.StudentName":"Carol"},{"StudentInformation.StudentName":"Bob"}]});這將產生以下輸出 -
{ "_id" : ObjectId("5e08b58625ddae1f53b6221a"), "StudentInformation" : [ { "StudentName" : "Carol", "StudentAge" : 19 }, { "StudentName" : "Bob", "StudentAge" : 18 } ] }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP