如何獲取 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" ]

更新日期: 2019-07-30

270 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

入門
廣告
© . All rights reserved.