You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js MongoDB:如何在分组查询中添加特定记录计数字段

问题与解决方案

原始数据结构

{_id: 1, name: 'joe', snapshot: null, age: 30}
{_id: 2, name: 'joe', snapshot: 'snapshot1', age: 30}
{_id: 3, name: 'joe', snapshot: 'snapshot15', age: 30}
{_id: 4, name: 'joe', snapshot: 'snapshot23', age: 30}

需求

按name字段分组查询,添加snapcount字段统计snapshot不为null的记录数量,期望输出格式如下:

{_id: 1, name: 'joe', snapcount: 3, age: 30}

遇到的问题

已能通过聚合操作实现分组,但无法得到上述期望的输出格式。

最终解决方案

重构数据结构为以下形式:

{
  _id: 1, 
  name: 'joe', 
  snapshots: [
    {name: 'snap17', id: 1},
    {name: 'snap15', id: 2},
    {name: 'snap14', id: 3}
  ], 
  age: 30
}

之后只需通过snapshots.length即可获取所需的统计数量,相关社区回答也提供了很大帮助。


内容的提问来源于stack exchange,提问作者Emme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 17:01:18