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

Làm cách nào để lấy một giá trị từ MongoDB theo tên khóa của nó?


Để truy xuất một giá trị từ MongoDB theo tên khóa của nó, hãy sử dụng cú pháp sau -

db.yourCollectionName.find({},{"yourFieldName":1}).pretty();

Để 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.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Larry","CustomerAge":21,"CustomerCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9163b5a56efcc0f9e69048")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Chris","CustomerAge":24,"CustomerCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9163c4a56efcc0f9e69049")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Mike","CustomerAge":26,"CustomerCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9163d3a56efcc0f9e6904a")
}

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 (). Truy vấn như sau -

> db.retrieveValueFromAKeyDemo.find().pretty();

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

{
   "_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
   "CustomerName" : "Larry",
   "CustomerAge" : 21,
   "CustomerCountryName" : "US"
}
{
   "_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
   "CustomerName" : "Chris",
   "CustomerAge" : 24,
   "CustomerCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
   "CustomerName" : "Mike",
   "CustomerAge" : 26,
   "CustomerCountryName" : "UK"
}

Đây là truy vấn để lấy một giá trị từ MongoDB theo tên khóa của nó, tức là chúng tôi đã coi khóa là 'CustomerCountryName' -

> db.retrieveValueFromAKeyDemo.find({},{"CustomerCountryName":1}).pretty();

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

{
   "_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
   "CustomerCountryName" : "US"
}
{
   "_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
   "CustomerCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
   "CustomerCountryName" : "UK"
}