從 MongoDB 集合中檢索資料?


如要在 MongoDB 中從集合返回單一文件,請使用 findOne()。我們建立一個包含文件的集合 -

> db.demo463.insertOne({"StudentName":"Chris
Brown","StudentAge":21,"StudentCountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7ec8cb66ccba22cc9dcf")
}
> db.demo463.insertOne({"StudentName":"David
Miller","StudentAge":23,"StudentCountryName":"UK"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7ed5cb66ccba22cc9dd0")
}
> db.demo463.insertOne({"StudentName":"John
Doe","StudentAge":22,"StudentCountryName":"AUS"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7ee1cb66ccba22cc9dd1")
}
> db.demo463.insertOne({"StudentName":"John
Smith","StudentAge":24,"StudentCountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7eefcb66ccba22cc9dd2")
}

使用 find() 方法從集合顯示全部文件 -

> db.demo463.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5e7f7ec8cb66ccba22cc9dcf"), "StudentName" : "Chris Brown",
"StudentAge" : 21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e7f7ed5cb66ccba22cc9dd0"), "StudentName" : "David Miller",
"StudentAge" : 23, "StudentCountryName" : "UK" }
{ "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"), "StudentName" : "John Doe", "StudentAge" :
22, "StudentCountryName" : "AUS" }
{ "_id" : ObjectId("5e7f7eefcb66ccba22cc9dd2"), "StudentName" : "John Smith", "StudentAge"
: 24, "StudentCountryName" : "US" }

以下是從 MongoDB 中檢索資料的查詢 -

> db.demo463.findOne({"StudentName":"John Doe"});

這將產生以下輸出 -

{
   "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"),
   "StudentName" : "John Doe",
   "StudentAge" : 22,
   "StudentCountryName" : "AUS"
}

更新時間: 11-May-2020

566 次檢視

開啟 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.