如何使用MongoDB根据数组元素对记录进行分组

时间:2019-05-07 17:46:12

标签: arrays mongodb mongoose nosql mongodb-query

我有一个数据收集,其中包含一组以下格式的记录。

{
    "_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"
    ]
}

请注意,“类别”是一个数组。

我想统计每个类别的已出版书籍。我尝试了以下解决方案,但将整个数组视为一组。

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

相反,我想计算“类别”数组中每个单独类别值的记录数。

1 个答案:

答案 0 :(得分:3)

您应该首先使用$unwind,它为数组中的每个元素输出一个文档。

{
  "REDIRECT_REDIRECT_SERVER_ADMIN": "admin@example.com",
  "REDIRECT_REDIRECT_PHPRC": "/home/user",
  "REDIRECT_REDIRECT_HTTPS": "on",
  "REDIRECT_REDIRECT_SSL_TLS_SNI": "www.example.com",
  "REDIRECT_REDIRECT_STATUS": "200",
  "REDIRECT_SERVER_ADMIN": "admin@example.com",
  "REDIRECT_PHPRC": "/home/user",
  "REDIRECT_HTTPS": "on",
  "REDIRECT_SSL_TLS_SNI": "www.example.com",
  "REDIRECT_STATUS": "200",
  "HTTPS": "on",
  "SSL_TLS_SNI": "www.example.com",
  "HTTP_HOST": "www.example.com",
  "REQUEST_METHOD": "DELETE",
  "REQUEST_URI": "/",
  "SCRIPT_NAME": "/index.php"
}