将每个日期的数据分配给两个类别时,按日期按日期按日期进行分组

发布于 2025-02-02 21:13:06 字数 399 浏览 3 评论 0原文

我正在研究一个类似于 this 和在那里发布的答案帮助我弄清楚了如何解决自己的问题。

我遇到的其他问题是 - 如果我希望以以下格式输出我的查询,该如何修改查询? :(

{"label": "2020-08-21", "value": 5, "A": 2, "Others": 3}

例如输出{“ label”:“ 2020-08-21”,“ value”:7,印度:3,其他:4})

提前谢谢! :)

I am working on a problem similar to this and the answer posted there helped me figure out how I can work with my problem.

Additional question I have is - how can I modify my query if I want my output in the following format? :

{"label": "2020-08-21", "value": 5, "A": 2, "Others": 3}

(example output {"label": "2020-08-21", "value": 7, India: 3, Others: 4})

Thank you in advance!! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦亿 2025-02-09 21:13:06

在这种情况下,您可以简单地分组:

db.collection.aggregate([
  {
    $project: {
      createdAt: {$dateToString: {format: "%Y-%m-%d", date: "$timestamp"}},
      recipe: 1
    }
  },
  {
    $group: {
      _id: "$createdAt",
      A: {$sum: {$cond: [{$eq: ["$recipe", "A"]}, 1, 0]}},
      value: {$sum: 1}
    }
  },
  {
    $project: {
      _id: 0, label: "$_id", value: 1, A: 1, other: {$subtract: ["$value", "$A"]}
    }
  }
])

Playground示例

In this case you can simply group:

db.collection.aggregate([
  {
    $project: {
      createdAt: {$dateToString: {format: "%Y-%m-%d", date: "$timestamp"}},
      recipe: 1
    }
  },
  {
    $group: {
      _id: "$createdAt",
      A: {$sum: {$cond: [{$eq: ["$recipe", "A"]}, 1, 0]}},
      value: {$sum: 1}
    }
  },
  {
    $project: {
      _id: 0, label: "$_id", value: 1, A: 1, other: {$subtract: ["$value", "$A"]}
    }
  }
])

Playground example

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文