获取 MongoDB 文档的所有 ID?

mongodbdatabasebig data analytics更新于 2026/1/10 3:07:17

要获取所有 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") }

相关文章