能否按字段名称分组?还是说我需要不同的结构以便可以按值进行分组?
我知道我们可以在值上使用group by,也可以展开数组,但是是否可能在这里获取John拥有的三个房屋中的苹果、梨子和桔子的总数,而不需要在查询中明确指定“苹果”、“梨子”和“桔子”?(所以不像这样);
// total all the fruit John has at each house
db.houses.aggregate([
{
$group: {
_id: null,
"apples": { $sum: "$people.John.items.apples" },
"pears": { $sum: "$people.John.items.pears" },
"oranges": { $sum: "$people.John.items.oranges" },
}
},
])
换句话说,我可以按照“items”下的第一个字段名称进行分组,并获得苹果:104,梨子:202和橙子:306的聚合总和,还有香蕉、甜瓜和其他可能存在的任何东西吗?还是需要将数据重构为类别的键值对数组?
db.createCollection("houses");
db.houses.remove();
db.houses.insert(
[
{
House: "birmingham",
categories : [
{
k : "location",
v : { d : "central" }
}
],
people: {
John: {
items: {
apples: 2,
pears: 1,
oranges: 3,
}
},
Dave: {
items: {
apples: 30,
pears: 20,
oranges: 10,
},
},
},
},
{
House: "London", categories: [{ k: "location", v: { d: "central" } }, { k: "type", v: { d: "rented" } }],
people: {
John: { items: { apples: 2, pears: 1, oranges: 3, } },
Dave: { items: { apples: 30, pears: 20, oranges: 10, }, },
},
},
{
House: "Cambridge", categories: [{ k: "type", v: { d: "rented" } }],
people: {
John: { items: { apples: 100, pears: 200, oranges: 300, } },
Dave: { items: { apples: 0.3, pears: 0.2, oranges: 0.1, }, },
},
},
]
);
其次,更重要的是,我是否可以按“house.categories.k”进行分组?换句话说,是否可以找出“John”在“rented”与“owned”或“friends”房屋中拥有多少“apples”(因此按“categories.k.type”分组)?
最后,如果这样做是可行的,那么它是否明智?起初,我认为使用对象的实际字段名称创建嵌套对象的字典非常有用,因为它似乎是文档数据库的逻辑用法,并且似乎比数组更容易编写MR查询,但现在我开始怀疑这是否都是一个坏主意,并且具有可变字段名称使得编写聚合查询非常棘手/低效。