简体   繁体   中英

MongoDB: Group values in nested array to get count

I've searched but could not find an answer to my problem. I've got a collection with this sample structure in MongoDB:

{
  "_id": ObjectID(1),
  "Manual_Tags": [
    {
      _source: {
        tags: [ "tag1", "tag2", "tag3"]
        other_values: ...
      }
    }
  ]
}
{
  "_id": ObjectID(2),
  "Manual_Tags": [
    {
      _source: {
        tags: [ "tag2", "tag3", "tag4"]
        other_values: ...
      }
    }
  ]
}

I need to know the count of instances for each value of "tags" existing in the collection for all documents (Manual_Tags[]._source.tags[]). That is, for the 2 documents in the sample above, the listing would be: tag1: 1 tag2: 2 tag3: 2 tag4: 1

Thanks in advance for any help.

You need to look at aggregation queries. First you need to unwind both the arrays and then just group on tags to get the count

db.collection.aggregate(
  {$unwind: '$Manual_Tags'},
  {$unwind: '$Manual_Tags._source.tags'},
  {$group: {_id: '$Manual_Tags._source.tags', count:{$sum:1}}}
)

Using Projections and Groups

db.mycollection.aggregate(
    [
        {
            $project: {
                _id:0,
                tag_count:{$size:"$Manual_Tags._source.tags"},
            }
        }, 
        {
            $group: {
                tag_total:{$sum:"$tag_count"},
            }
        }
    ]
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM