Bạn có thể chọn một trường trong MongoDB bằng cú pháp sau:
db.yourCollectionName.find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0}); Trong cú pháp trên "yourSingleFieldName":1, _id:0 có nghĩa là lấy tất cả dữ liệu từ một trường mà không có _id .
Để 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 tài liệu như sau:
> db.singleFieldDemo.insertOne({"StudentName":"David","StudentAge":28});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6eba356fd07954a489067c")
}
> db.singleFieldDemo.insertOne({"StudentName":"Bob","StudentAge":18});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6eba406fd07954a489067d")
}
> db.singleFieldDemo.insertOne({"StudentName":"Chris","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6eba4c6fd07954a489067e")
}
> db.singleFieldDemo.insertOne({"StudentName":"Robert","StudentAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6eba586fd07954a489067f")
} Bây giờ bạn có thể 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.singleFieldDemo.find().pretty();
Sau đây là kết quả:
{
"_id" : ObjectId("5c6eba356fd07954a489067c"),
"StudentName" : "David",
"StudentAge" : 28
}
{
"_id" : ObjectId("5c6eba406fd07954a489067d"),
"StudentName" : "Bob",
"StudentAge" : 18
}
{
"_id" : ObjectId("5c6eba4c6fd07954a489067e"),
"StudentName" : "Chris",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c6eba586fd07954a489067f"),
"StudentName" : "Robert",
"StudentAge" : 26
} Đây là truy vấn để chọn một trường:
> db.singleFieldDemo.find({"StudentAge":18},{"StudentName":1,"_id":0}); Sau đây là kết quả:
{ "StudentName" : "Bob" }