【问题标题】:MongoDB - Multiple query and single document resultMongoDB - 多个查询和单个文档结果
【发布时间】:2017-03-13 07:35:44
【问题描述】:

我正在创建一个洞察仪表板,我有一些数据和存储的计数,但我需要将其合并到一个文档中。 (嗯,很难用语言来解释),例如

网站集:

{
 Name: "..."
 ApiKey: "SomeUnique1"
 Insights:
 {
   sumOfData: 5,
   anotherSum: 14
 }
},
{
     Name: "..."
     ApiKey: "SomeUnique2"
     Insights:
     {
       sumOfData: 5,
       anotherSum: 1
     }
    },...

我想检索以下数据:

{
     ChartDashboard: "Usage"
     Insights:
     {
       sumOfData: 10,
       anotherSum: 15
     }
    }

我读到 $and 运算符可以使用一些 ApiKey 的属性进行检索,但是 MongoDB 有任何运算符可以做到这一点?

【问题讨论】:

  • 为此使用聚合。看看$group 运算符
  • 嗯,是的!这很有帮助

标签: javascript node.js mongodb mongoose query-optimization


【解决方案1】:

您可以使用聚合框架。一个例子如下:

db.collection.aggregate([
{ '$group':
   {
    _id:null, 
   'ChartDashboard':'Usage',
   'sumOfData':{$sum:'$Insights.sumOfData'},
   'anotherSum':{$sum:'$Insights.sumOfData'}
   }
}
])

结果将是:

{
    '_id' : null,
    'ChartDashboard' : 'Usage',
    'sumOfData' : 10,
    'anotherSum' : 15 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多