1

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 Answer 1

3

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 } }
  }   
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.