獲取所有 MongoDB 文件的 ID?


若要獲取所有 ID,只需在 MongoDB 中使用 find()。我們建立一個包含文件的集合 -

> db.demo169.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e36975e9e4f06af551997d7")
}
> db.demo169.insertOne({"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3697629e4f06af551997d8")
}
> db.demo169.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3697679e4f06af551997d9")
}

在集合中顯示所有文件,方法是使用 find() 方法 -

> db.demo169.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5e36975e9e4f06af551997d7"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e3697629e4f06af551997d8"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e3697679e4f06af551997d9"), "StudentName" : "David" }

以下是查詢,用於獲取集合中所有 MongoDB 文件的文件 ID -

> var iterator=db.demo169.find({},{"StudentName":0});

在集合中顯示所有文件,方法是使用 find() 方法 -

> iterator;

這將產生以下輸出 -

{ "_id" : ObjectId("5e36975e9e4f06af551997d7") }
{ "_id" : ObjectId("5e3697629e4f06af551997d8") }
{ "_id" : ObjectId("5e3697679e4f06af551997d9") }

更新於:2020 年 4 月 1 日

1K+ 瀏覽

開啟您的 職業生涯

完成課程,獲取認證

開始學習
廣告
© . All rights reserved.