Computer >> Máy Tính >  >> Lập trình >> MongoDB

Lấy tất cả các tên cột trong một bảng trong MongoDB


Trong MongoDB, không có khái niệm cột vì MongoDB là lược đồ ít hơn và không chứa bảng. Nó chứa đựng khái niệm về bộ sưu tập và bộ sưu tập có các loại tài liệu khác nhau để lưu trữ các mục.

Hãy cho chúng tôi xem cú pháp -

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

Nếu bạn muốn một bản ghi từ một tập hợp, bạn có thể sử dụng findOne () và để lấy tất cả các bản ghi từ tập hợp, bạn có thể sử dụng find ().

Cú pháp như sau -

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

Để hiểu cú pháp trên, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -

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

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Như đã thảo luận ở trên find (), nó sẽ trả về tất cả các bản ghi.

Truy vấn như sau -

> db.collectionOnDifferentDocumentDemo.find();

Sau đây là kết quả -

{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c953ba4749816a0ce933683"), "UserName" : "David", "UserAge" : 24 }
{ "_id" : ObjectId("5c953bb8749816a0ce933684"), "UserName" : "Carol", "UserAge" : 25, "UserCountryName" : "US" }

Hiển thị một bản ghi từ một bộ sưu tập với sự trợ giúp của phương thức findOne (). Truy vấn như sau -

> db.collectionOnDifferentDocumentDemo.findOne();

Sau đây là kết quả -

{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }