如何在MongoDB中获得不同的子文档字段值列表?

若要获取不同的子文档字段值列表,可以使用dot(。)。语法如下-

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()method的帮助下显示集合中的所有文档。查询如下-

> 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" ]