僅顯示 MongoDB 儲存庫中所有文件的單個欄位


投影表示只有所選欄位才應可見。如果要使其可見,則將該欄位設為 1。

讓我們先使用文件建立一個集合 -

> db.demo384.insertOne({"StudentName":"Chris Brown","StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b67a022064be7ab44e7f2")
}
> db.demo384.insertOne({"StudentName":"David Miller","StudentCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b67ab22064be7ab44e7f3")
}
> db.demo384.insertOne({"StudentName":"John Doe","StudentCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b67b422064be7ab44e7f4")
}

使用 find() 方法從集合顯示所有文件 -

> db.demo384.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5e5b67a022064be7ab44e7f2"), "StudentName" : "Chris Brown", "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e5b67ab22064be7ab44e7f3"), "StudentName" : "David Miller", "StudentCountryName" : "AUS" }
{ "_id" : ObjectId("5e5b67b422064be7ab44e7f4"), "StudentName" : "John Doe", "StudentCountryName" : "UK" }

以下是僅顯示單個欄位並忽略其他欄位的查詢 -

> db.demo384.find({},{_id:0,StudentName:0});

這將產生以下輸出 -

{ "StudentCountryName" : "US" }
{ "StudentCountryName" : "AUS" }
{ "StudentCountryName" : "UK" }

更新於: 2020 年 4 月 2 日

660 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始使用
廣告