하위 문서 필드 값의 고유한 목록을 얻으려면 점(.)을 사용할 수 있습니다. 구문은 다음과 같습니다 -
db.yourCollectionName.distinct("yourOuterFieldName.yourInnerFieldName"); 개념을 이해하기 위해 문서로 컬렉션을 만들어 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다 -
> 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")
} find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다 -
> db.getDistinctListOfSubDocumentFieldDemo.find().pretty();
다음은 출력입니다 -
{
"_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
}
]
} 다음은 하위 문서 필드 값의 고유한 목록을 가져오는 쿼리입니다. -
> db.getDistinctListOfSubDocumentFieldDemo.distinct("StudentPersonalDetails.StudentName"); 다음은 출력입니다 -
[ "Carol", "John", "Bob", "David" ]