MongoDB: How to get distinct list of sub-document field values?

后端 未结 2 2062
时光取名叫无心
时光取名叫无心 2020-12-08 10:04

Let\'s say I have the following documents in collection:

{
   \"family\": \"Smith\",
   \"children\": [
        {
            \"child_name\": \"John\"
               


        
相关标签:
2条回答
  • 2020-12-08 10:35

    You can just do:

    db.collection.distinct("children.child_name");
    

    In your case it returns:

    [ "John", "Anna", "Kevin" ]
    
    0 讨论(0)
  • 2020-12-08 10:53

    with the help aggregation framework:

    db.collection.aggregate([{$unwind:'$children'}, {$group:{_id:'$children.child_name'}}])
    

    or more interest ;) with frequency of name:

    db.collection.aggregate([{$unwind:'$children'}, {$group:{_id:'$children.child_name', freq:{$sum:1}}}])
    
    0 讨论(0)
提交回复
热议问题