本文介绍了如何使用MongoDB根据数组元素对记录进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据收集,其中包含一组以下格式的记录.
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" : "s3.amazonaws/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" : "s3.amazonaws/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.
推荐答案您应首先使用 $ unwind ,它为数组中的每个元素输出一个文档.
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 } } } ])更多推荐
如何使用MongoDB根据数组元素对记录进行分组
发布评论