【问题标题】:How to group records based on array elements using MongoDB如何使用 MongoDB 根据数组元素对记录进行分组
【发布时间】:2019-09-25 10:23:54
【问题描述】:

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

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

而不是这样,我想计算“类别”数组中每个单独类别值的记录数。

【问题讨论】:

    标签: arrays mongodb mongoose nosql mongodb-query


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多