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

编程入门 行业动态 更新时间:2024-10-28 02:27:24
本文介绍了如何使用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根据数组元素对记录进行分组

本文发布于:2023-10-27 18:36:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534200.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   如何使用   元素   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!