获取MongoDB表中的所有列名

在MongoDB中,没有列的概念,因为MongoDB是无架构的,并且不包含表。它包含集合的概念,并且集合具有用于存储项目的不同类型的文档。

让我们看看语法-

db.yourCollectionName.insertOne({“YourFieldName”:yourValue, “yourFieldName”:”yourValue”,.......N});

如果要从集合中获取一条记录,则可以使用findOne(),为了从集合中获取所有记录,可以使用find()。

语法如下-

db.yourCollectionName.findOne(); //Get Single Record
db.yourCollectionName.find(); // Get All Record

为了理解上述语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-

> 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" }