Để có được danh sách riêng biệt của các giá trị trường tài liệu con, bạn có thể sử dụng dấu chấm (.). Cú pháp như sau -
db.yourCollectionName.distinct("yourOuterFieldName.yourInnerFieldName"); Để hiểu khái niệm, 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.getDistinctListOfSubDocumentFieldDemo.insertOne(
... {
... "StudentId": 101,
... "StudentPersonalDetails": [
... {
... "StudentName": "John",
... "StudentAge":24
... },
... {
... "StudentName": "Carol",
... "StudentAge":21
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90a9abb74d7cfe6392d7d8")
}
> db.getDistinctListOfSubDocumentFieldDemo.insertOne(
...
... {
... "StudentId": 102,
... "StudentPersonalDetails": [
... {
... "StudentName": "Carol",
... "StudentAge":26
... },
... {
... "StudentName": "Bob",
... "StudentAge":21
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90a9ceb74d7cfe6392d7d9")
}
> db.getDistinctListOfSubDocumentFieldDemo.insertOne(
... {
... "StudentId": 103,
... "StudentPersonalDetails": [
... {
... "StudentName": "Bob",
... "StudentAge":25
... },
... {
... "StudentName": "David",
... "StudentAge":24
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90a9e6b74d7cfe6392d7da")
} 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.getDistinctListOfSubDocumentFieldDemo.find().pretty();
Sau đây là kết quả -
{
"_id" : ObjectId("5c90a9abb74d7cfe6392d7d8"),
"StudentId" : 101,
"StudentPersonalDetails" : [
{
"StudentName" : "John",
"StudentAge" : 24
},
{
"StudentName" : "Carol",
"StudentAge" : 21
}
]
}
{
"_id" : ObjectId("5c90a9ceb74d7cfe6392d7d9"),
"StudentId" : 102,
"StudentPersonalDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 26
},
{
"StudentName" : "Bob",
"StudentAge" : 21
}
]
}
{
"_id" : ObjectId("5c90a9e6b74d7cfe6392d7da"),
"StudentId" : 103,
"StudentPersonalDetails" : [
{
"StudentName" : "Bob",
"StudentAge" : 25
},
{
"StudentName" : "David",
"StudentAge" : 24
}
]
} Đây là truy vấn để nhận danh sách riêng biệt của các giá trị trường tài liệu con -
> db.getDistinctListOfSubDocumentFieldDemo.distinct("StudentPersonalDetails.StudentName"); Sau đây là kết quả -
[ "Carol", "John", "Bob", "David" ]