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

后端 未结 2 2065
时光取名叫无心
时光取名叫无心 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: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}}}])
    

提交回复
热议问题