Get the App
SLTechnology News&Howtos  ›  Database  › 

How to realize the grouping of nested subdocuments in MongoDB

Shulou Source: shulou.com Published: 2022-05-31 21:16:31 09月14日 Update

This article is to share with you about how to achieve nested sub-document grouping in MongoDB, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

The data of MongoDB nested structure is very common, it achieves an one-to-many relationship by nesting subdocuments. However, the data calculation of subdocuments according to classification and grouping in the nested structure can not be directly realized by the $group aggregation operation. It is necessary to unravel the nested structure and change it from a multi-layer nested structure to a multi-layer single-layer structure. Because of the processing of the intermediate process, and other functions are needed to assist the output. Taking the collection order as an example, the number of term is grouped by category and output in the order from largest to smallest.

[

{category: "movies"

Terms: [{term: "movie 1", total: 1000}, {term: "movie 2", total: 100}]

}

{category: "sports"

Terms: [{term: "football 1", total: 1000}, {term: "tennis 2", total: 120}]

}

{category: "movies"

Terms: [{term: "movie 1", total: 5000}, {term: "movie 2", total: 200}

{term: "movie 3", total: 280}]

}

{category: "sports"

Terms: [{term: "football 1", total: 4000}, {term: "tennis 2", total: 4000}

{term: "tennis 2", total: 450}]

}

]

MongoDB is implemented through the aggregation operation aggregate,group as follows:

Db.order.aggregate ([

{$unwind: "$terms"}

{$group: {_ id: {

Category: "$category"

Term: "$terms.term"}

Total: {$sum: "$terms.total"}

}

}

{$sort: {total:-1}}

{$project: {

_ id: 0

Category: "$_ id.category"

Term: "$_ id.term"

Total:1}}

])

$unwind splits the terms array into multiple strips, then grouped, summed, sorted by $group, and finally filtered the field output with $project.

If there were aggregators to assist MongoDB, there would be no need for such tedious combinatorial operations:

A1=mongo_open ("mongodb://127.0.0.1:27017/raqdb") 2=mongo_shell (A1, "order.find ()). Fetch () 3=A2.conj (terms.derive (A2.category)) 4=A5.group (category,term;~.sum (total): total). Sort (- total) 5 > A1.close () is how to achieve nested subdocument grouping in MongoDB. Xiaobian believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Grouping structure document sleeve output operation multiple data more knowledge article practical tedious function single layer multi-layer field that is work meeting common Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MariaDB Docker MySQL Microsoft