如何獲取 MongoDB 中子文件欄位值的唯一列表?
若要獲取子文件欄位值的唯一列表,可使用點 (.)。語法如下:-
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" ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP