首页 文章

Mongodb嵌入式文档 - 聚合查询

提问于
浏览
0

我在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 }

So, How can I modify the above query to return only the count of apples exported from UK ? Also, is there any other better way to achieve the output without unwinding ?

1 回答

  • 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"}}
    );
    

相关问题