How to group records based on array elements using

2019-07-31 05:24发布

问题:

I have a data collection which contains a set of records in the following format.

{
    "_id" : 22,
    "title" : "3D User Interfaces with Java 3D",
    "isbn" : "1884777902",
    "pageCount" : 520,
    "publishedDate" : ISODate("2000-08-01T07:00:00Z"),
    "thumbnailUrl" : "https://s3.amazonaws.com/AKIAJC5RLADLUMVRPFDQ.book-thumb-images/barrilleaux.jpg",
    "longDescription" : "Description",
    "status" : "PUBLISH",
    "authors" : [
        "Jon Barrilleaux"
    ],
    "categories" : [
        "Java",
        "Computer Graphics"
    ]
},
{
    "_id" : 23,
    "title" : "Specification by Example",
    "isbn" : "1617290084",
    "pageCount" : 0,
    "publishedDate" : ISODate("2011-06-03T07:00:00Z"),
    "thumbnailUrl" : "https://s3.amazonaws.com/AKIAJC5RLADLUMVRPFDQ.book-thumb-images/adzic.jpg",
    "status" : "PUBLISH",
    "authors" : [
        "Gojko Adzic"
    ],
    "categories" : [
        "Software Engineering"
    ]
}

Please note that the 'categories' is an array.

I want to count the published books for each category. I tried the following solution, but it treated the entire array as one group.

db.books.aggregate([
    {
        $group:{_id:"$categories", total:{$sum:1}}
    }
])

Instead of so, I want to count the number of records for each individual category value inside 'categories' array.

回答1:

You should first use $unwind which outputs one document for each element in the array.

db.books.aggregate([
  { 
    $unwind : "$categories"
  },
  {
    $group : { _id : "$categories", total: { $sum: 1 } }
  }   
])