我在Mongo数据库中有以下文件:
db.totaldemands.insert({ "data" : "UKToChina", "demandPerCountry" :
{ "from" : "UK" , to: "China" ,
"demandPerItem" : [ { "item" : "apples" , "demand" : 200 },
{ "item" : "plums" , "demand" : 100 }
] } });
db.totaldemands.insert({ "data" : "UKToSingapore",
"demandPerCountry" : { "from" : "UK" , to: "Singapore" ,
"demandPerItem" : [ { "item" : "apples" , "demand" : 100 },
{ "item" : "plums" , "demand" : 50 }
] } });
我需要写一个查询来查找从英国出口到任何国家/地区的苹果数量。
我尝试了以下查询:
db.totaldemands.aggregate(
{ $match : { "demandPerCountry.from" : "UK" ,
"demandPerCountry.demandPerItem.item" : "apples" } },
{ $unwind : "$demandPerCountry.demandPerItem" },
{ $group : { "_id" : "$demandPerCountry.demandPerItem.item",
"total" : { $sum : "$demandPerCountry.demandPerItem.demand"
} } }
);
但它给了我苹果和李子的输出,如下所示:
{ "_id" : "apples", "total" : 300 }
{ "_id" : "plums", "total" : 150 }
但是,我的预期输出是:
{ "_id" : "apples", "total" : 300 }
那么,如何修改上述查询以仅返回从英国出口的苹果数量? 另外,还有其他更好的方法来实现输出而不需要展开吗?
答案 0 :(得分:1)
您可以添加另一个 $ match 以仅获取苹果。
由于您已嵌入文档结构并执行聚合,因此此处需要$ unwind。备用选项可以是map和reduce。但是,放松最适合这里。
如果您正在考虑性能,则放松不应导致性能问题。
db.totaldemands.aggregate(
{ $match : { "demandPerCountry.from" : "UK" ,
"demandPerCountry.demandPerItem.item" : "apples" } },
{ $unwind : "$demandPerCountry.demandPerItem" },
{ $group : { "_id" : "$demandPerCountry.demandPerItem.item",
"total" : { $sum : "$demandPerCountry.demandPerItem.demand"
} } },
{$match : {"_id" : "apples"}}
);