Bạn có thể sử dụng phương thức difference () trong MongoDB để nhận các giá trị bản ghi riêng biệt. Cú pháp như sau -
db.yourCollectionName.distinct(“yourFieldName”);
Để 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.distinctRecordDemo.insertOne({"StudentId":1,"StudentName":"John","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a78299b97a65744c1b50")
}
> db.distinctRecordDemo.insertOne({"StudentId":2,"StudentName":"John","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a78b99b97a65744c1b51")
}
> db.distinctRecordDemo.insertOne({"StudentId":3,"StudentName":"Carol","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a79a99b97a65744c1b52")
}
> db.distinctRecordDemo.insertOne({"StudentId":4,"StudentName":"Carol","StudentAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a7a499b97a65744c1b53")
}
> db.distinctRecordDemo.insertOne({"StudentId":5,"StudentName":"Sam","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a7b499b97a65744c1b54")
}
> db.distinctRecordDemo.insertOne({"StudentId":6,"StudentName":"Mike","StudentAge":27});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a7c799b97a65744c1b55")
}
> db.distinctRecordDemo.insertOne({"StudentId":7,"StudentName":"Sam","StudentAge":28});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a7d399b97a65744c1b56")
} 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.distinctRecordDemo.find().pretty();
Sau đây là kết quả:
{
"_id" : ObjectId("5c77a78299b97a65744c1b50"),
"StudentId" : 1,
"StudentName" : "John",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c77a78b99b97a65744c1b51"),
"StudentId" : 2,
"StudentName" : "John",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c77a79a99b97a65744c1b52"),
"StudentId" : 3,
"StudentName" : "Carol",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c77a7a499b97a65744c1b53"),
"StudentId" : 4,
"StudentName" : "Carol",
"StudentAge" : 26
}
{
"_id" : ObjectId("5c77a7b499b97a65744c1b54"),
"StudentId" : 5,
"StudentName" : "Sam",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c77a7c799b97a65744c1b55"),
"StudentId" : 6,
"StudentName" : "Mike",
"StudentAge" : 27
}
{
"_id" : ObjectId("5c77a7d399b97a65744c1b56"),
"StudentId" : 7,
"StudentName" : "Sam",
"StudentAge" : 28
} Đây là truy vấn để nhận các giá trị bản ghi riêng biệt trong MongoDB.
Trường hợp 1 - Đây là trường “StudentName”.
Truy vấn như sau -
> db.distinctRecordDemo.distinct("StudentName"); Sau đây là kết quả hiển thị bản ghi riêng biệt cho StudentName -
[ "John", "Carol", "Sam", "Mike" ]
Trường hợp 2 - Đây là trường “StudentAge”.
Truy vấn như sau -
> db.distinctRecordDemo.distinct("StudentAge"); Sau đây là đầu ra hiển thị bản ghi riêng biệt cho StudentAge -
[ 21, 22, 26, 24, 27, 28 ]