获取 MongoDB 中表的所有列名
mongodbdatabasebig data analytics更新于 2026/1/23 2:37:17
MongoDB 中没有列的概念,因为 MongoDB 是无模式的,并且不包含表。它包含集合的概念,而集合包含不同类型的文档来存储项目。
让我们看看语法 −
db.yourCollectionName.insertOne({“YourFieldName”:yourValue, “yourFieldName”:”yourValue”,.......N});
如果要从集合中获取单条记录,可以使用 findOne();如果要从集合中获取所有记录,可以使用 find()。
语法如下 −
db.yourCollectionName.findOne(); //获取单条记录 db.yourCollectionName.find(); // 获取所有记录
为了理解上述语法,让我们创建一个包含文档的集合。创建包含文档的集合的查询如下 −
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c953b98749816a0ce933682")
}
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"David","UserAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c953ba4749816a0ce933683")
}
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"Carol","UserAge":25,"UserCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c953bb8749816a0ce933684")
}
使用 find() 方法显示集合中的所有文档。如上所述,find() 将返回所有记录。
查询如下 −
> db.collectionOnDifferentDocumentDemo.find();
以下是输出 −
{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c953ba4749816a0ce933683"), "UserName" : "David", "UserAge" : 24 }
{ "_id" : ObjectId("5c953bb8749816a0ce933684"), "UserName" : "Carol", "UserAge" : 25, "UserCountryName" : "US" }
使用 findOne() 方法显示集合中的单条记录。查询如下 −
> db.collectionOnDifferentDocumentDemo.findOne();
以下是输出 −
{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }

