如何根據特定屬性用 MongoDB 顯示物件列表?
要根據特定屬性顯示物件列表,在 find() 中使用點表示法。讓我們建立帶文件的集合 -
> db.demo455.insertOne({"Information":{"Student":[{"Name":"Chris","Age":22}]}});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7e1876dbcb9adb296c95c5")
}
> db.demo455.insertOne({"Information":{"Student":[{"Name":"David","Age":21}]}});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7e1883dbcb9adb296c95c6")
}
> db.demo455.insertOne({"Information":{"Student":[{"Name":"Bob","Age":24}]}});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7e188adbcb9adb296c95c7")
}
> db.demo455.insertOne({"Information":{"Student":[{"Name":"Robert","Age":21}]}});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7e18bcdbcb9adb296c95c8")
}使用 find() 方法從集合中顯示所有文件 -
> db.demo455.find();
將生成以下輸出 -
{ "_id" : ObjectId("5e7e1876dbcb9adb296c95c5"), "Information" : { "Student" : [ { "Name" :
"Chris", "Age" : 22 } ] } }
{ "_id" : ObjectId("5e7e1883dbcb9adb296c95c6"), "Information" : { "Student" : [ { "Name" :
"David", "Age" : 21 } ] } }
{ "_id" : ObjectId("5e7e188adbcb9adb296c95c7"), "Information" : { "Student" : [ { "Name" :
"Bob", "Age" : 24 } ] } }
{ "_id" : ObjectId("5e7e18bcdbcb9adb296c95c8"), "Information" : { "Student" : [ { "Name" :
"Robert", "Age" : 21 } ] } }以下是根據特定屬性顯示物件列表的查詢 -
> db.demo455.find({"Information.Student.Age":21});將生成以下輸出 -
{ "_id" : ObjectId("5e7e1883dbcb9adb296c95c6"), "Information" : { "Student" : [ { "Name" :
"David", "Age" : 21 } ] } }
{ "_id" : ObjectId("5e7e18bcdbcb9adb296c95c8"), "Information" : { "Student" : [ { "Name" :
"Robert", "Age" : 21 } ] } }
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP