如何编写mongoDB查询来汇总数组中与另一个数组匹配的元素? [英] How to write mongoDB query to sum up elements in an array that match another array?

查看:209
本文介绍了如何编写mongoDB查询来汇总数组中与另一个数组匹配的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的mongoDB dbs中有一个集合A1,它有一个嵌入对象B的数组。我想用A1的数组字段中的某个字段B的总和来组合A1中的所有元素,即X. X字段的值必须是另一个集合A2中的元素。也就是说我需要总结B数组中的元素,其中X字段与A2集合中的元素匹配,用于分组A1而不是总结B数组中的所有元素。我写了一个查询,但不知道它是否正确。如果没有,如何将其修改为正确的?

In my mongoDB dbs there is a collection A1 that has an array of embedded objects B. I want to group all elements in A1 by the sum of a certain field of B in the array field of A1,namely X. Meanwhile the value of X field need to be an element in another collection A2. That's to say I need to sum up the elements in B array with the X field matching the elements in A2 collection for grouping A1 rather than sum up all elements in B array. I have wrote a query but don't know if it's correct. If not, how to modify it to the right one?

db.A1.aggregate([{$match:{B.X: {$in:A2}}},
                 {$group:{_id:"$ID",Sum: { $sum:"$B.X"}}},
                 {$sort:{Sum: 1}}
                ])

推荐答案

匹配:{BX:{


in:A2} },
{
in:A2}}}, {


group:{_ id:
group:{_id:"


这篇关于如何编写mongoDB查询来汇总数组中与另一个数组匹配的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆