Để phân biệt từ đầu tiên với một chuỗi, bạn có thể sử dụng diff (). Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.distinctFirstWordDemo.insertOne(
{
"_id": 100,
"StudentName":"John",
"StudentFeature": "John is a good player",
"Subject":"MongoDB"
}
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.distinctFirstWordDemo.insertOne(
{
"_id": 101,
"StudentName":"Carol",
"StudentFeature": "Carol is not a good player",
"Subject":"MongoDB"
}
);
{ "acknowledged" : true, "insertedId" : 101 } 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 () -
> db.distinctFirstWordDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : 100,
"StudentName" : "John",
"StudentFeature" : "John is a good player",
"Subject" : "MongoDB"
}
{
"_id" : 101,
"StudentName" : "Carol",
"StudentFeature" : "Carol is not a good player",
"Subject" : "MongoDB"
} Sau đây là truy vấn để nhận từ đầu tiên khác biệt từ một chuỗi -
> student = db.distinctFirstWordDemo.distinct("StudentFeature", {"Subject" : "MongoDB"}).map(function(st){
return st.split(" ")[0];
});
[ "John", "Carol" ]
> printjson(student); Điều này sẽ tạo ra kết quả sau -
[ "John", "Carol" ]