Request and summarize everything with mongoose

I want to get all users user_totaldocs and user_totalthings and I want to summarize these variables.

How is this possible? Here is the user diagram:

 var user_schema = mongoose.Schema({ local : { ... ... user_id : String, user_totaldocs : Number, user_totalthings : Number .... } }); 
+5
source share
2 answers

You can use the Aggregation Pipeline to add calculated fields to the result. The following are some examples of using the mongo shell, but the syntax in the Mongoose Aggregate () utility is similar.

For example, to calculate the amounts (for each user document), you can use the $add expression in the $project stage :

 db.user.aggregate( // Limit to relevant documents and potentially take advantage of an index { $match: { user_id: "foo" }}, { $project: { user_id: 1, total: { $add: ["$user_totaldocs", "$user_totalthings"] } }} ) 

To calculate the totals for several documents, you need to use the $group stage with $sum accumulator , for example:

 db.user.aggregate( { $group: { _id: null, total: { $sum: { $add: ["$user_totaldocs", "$user_totalthings"] } }, totaldocs: { $sum: "$user_totaldocs" }, totalthings: { $sum: "$user_totalthings" } }} ) 

You may need only one total field; I have added examples of calculating several fields in totaldocs and totalthings .

The _id of null group will combine the values ​​from all documents submitted to the $group stage, but you can also use other criteria (for example, group by user_id ).

+12
source

You can use the aggregation structure provided by mongodb. For your case -

if you want to get the amount of user_totaldocs and the amount of user_totalthings for the entire collection (which means for all users), do -

 db.user_schemas.aggregate( [ { $group : { user_id : null, user_totaldocs: { $sum: "$user_totaldocs"}, // for your case use local.user_totaldocs user_totalthings: { $sum: "$user_totalthings" }, // for your case use local.user_totalthings count: { $sum: 1 } // for no. of documents count } } ]) 

Summarize user_totaldocs and user_totalthings for a specific user in the collection (assuming there are several documents for the user), this will return the amount for each user, DO -

 db.user_schemas.aggregate( [ { $group : { user_id : "$user_id", user_totaldocs: { $sum: "$user_totaldocs"}, // for your case use local.user_totaldocs user_totalthings: { $sum: "$user_totalthings" }, // for your case use local.user_totalthings count: { $sum: 1 } // for no. of documents count } } ]) 

No need to provide an individual user ID.

Read more: 1. http://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group 2. http://docs.mongodb.org/manual/core/aggregation/

+4
source

Source: https://habr.com/ru/post/1201363/


All Articles