MongoDB 一条数据输出一个字段不同的值的count值

本文介绍了如何在MongoDB中通过过滤、分组操作统计同一agentId下,不同userId的type为'AAA'和'BBB'的次数。通过示例代码展示了从原始数据到最终期望结果的处理过程。

1. 数据如下:

数据1:
数据

2. 想要输出同一个 agentId 下面,每个userId,type是AAA的次数和BBB的次数

一上来可能有点复杂,我们一步一步慢慢来,先简化一下,好整理思路

3. 输出agentId是123,userId是yellow,type是AAA的次数和BBB的次数

3.1 先过滤一下

这里写图片描述

3.2 再分组

在SQL里面,语法是select count(a) from xx group by a

我们在MongoDB里写一下类似的
代码:

db.test_yellow.aggregate([
{
  $match : {
    "agentId" : "123",
    "userId" : "yellow"
  }
},
{
  $group: {
    _id: {
      "targetType": "$targetType"
      },
    count: {$sum:1}
  }
}
])

输出为

{ 
    "_id" : {
        "targetType" : "BBB"
    }, 
    "count" : 1.0
}
{ 
    "_id" : {
        "targetType" : "AAA"
    }, 
    "count" : 2.0
}

虽然数据是对的,但是结果有两条数据,不符合我们的标题,
我们希望的是,在一条数据里输出两个值,类似于

{     
    "count" : 2.0,
    "AAACount": 2.0,
    "BBBCount": 1.0
}

3.3 此时,就是合并数据的操作了

但是,我搜了好久的资料,不知道怎么合并,放弃之

同事提醒了我,用project试试

3.4 增加字段

代码:

db.test_yellow.aggregate([
{
  $match : {
    "agentId"   : "123",
    "userId" : "yellow"
  }
},
{
  $project: {
    _id: 1,
    "targetType": 1,
    "agentId": 1,
    "userId": 1,
    AType: {
      $cond: {
        if: {$eq: ["AAA", "$targetType"]},
        then: 1,
        else: 0
      }
    },
    BType: {
        $cond: {
            if: {$eq: ["BBB", "$targetType"]},
            then: 1,
            else: 0
        }
    }
  }
}
])

结果如下:
这里写图片描述

可以看到根据不同的类型,新增了字段,并且把自己设置数字1
方便后面统计

3.5 group 统计

代码:

db.test_yellow.aggregate([
{
  $match : {
    "agentId"   : "123",
    "userId" : "yellow"
  }
},
{
  $project: {
    _id: 1,
    "targetType": 1,
    "agentId": 1,
    "userId": 1,
    AType: {
      $cond: {
        if: {$eq: ["AAA", "$targetType"]},
        then: 1,
        else: 0
      }
    },
    BType: {
        $cond: {
            if: {$eq: ["BBB", "$targetType"]},
            then: 1,
            else: 0
        }
    }
  }
},
{
  $group: {
    _id: {
        "targetType": "$targetType"
    },
    totalCount: {$sum: 1},
    ACount: {$sum: "$AType"},
    BCount: {$sum: "$BType"}
  }
}
])

输出如下:
这里写图片描述

4. 最后

综上所述,可以写出最终的代码:

db.test_yellow.aggregate([
{
  $project: {
    _id: 1,
    "targetType": 1,
    "agentId": 1,
    "userId": 1,
    AType: {
      $cond: {
        if: {$eq: ["AAA", "$targetType"]},
        then: 1,
        else: 0
      }
    },
    BType: {
        $cond: {
            if: {$eq: ["BBB", "$targetType"]},
            then: 1,
            else: 0
        }
    }
  }
},
{
  $group: {
    _id: {
        "agentId": "$agentId",
        "userId": "$userId"
    },
    agentId: {$first: "$agentId"},
    userId: {$first: "$userId"},
    totalCount: {$sum: 1},
    ACount: {$sum: "$AType"},
    BCount: {$sum: "$BType"}
  }
}
])

输出
这里写图片描述

可以看到输出结果是符合预期的

<think>我们正在讨论MongoDB中更新单个文档的操作。根据用户的问题,他想知道如何使用updateOne来更新单个文档。 根据引用[4],updateOne的基本语法是: db.collection.updateOne( <filter>, <update>, { upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string> } ) 其中: - <filter>:用于选择要更新的文档的查询条件。 - <update>:指定要应用的修改操作,通常使用更新运算符(如$set, $inc等)。 - 可选参数包括upsert(如果为true,当没有匹配文档时插入新文档)、writeConcern(写关注)、collation(排序规则)、arrayFilters(用于更新数组中的特定元素)和hint(指定使用的索引)。 例如,我们有一个名为“users”的集合,其中包含文档: { "_id": 1, "name": "Alice", "age": 25, "status": "active" } 如果我们想将_id为1的文档的age更新为26,并添加一个字段“email”,我们可以这样写: db.users.updateOne( { "_id": 1 }, { $set: { "age": 26, "email": "alice@example.com" } } ) 如果更新成功,将返回一个结果对象,其中包含匹配的文档数(matchedCount)和修改的文档数(modifiedCount),通常都是1。 另外,引用[2]也提到,更新多个参数时可以使用$set运算符来设置多个字段。 需要注意的是,如果不使用更新运算符(如$set),而直接提供一个文档,那么整个文档将被替换(覆盖更新)。但在updateOne中,我们通常使用更新运算符来修改部分字段。 因此,我们可以这样总结步骤: 1. 选择要更新的集合(db.collection)。 2. 使用updateOne方法,第一个参数是过滤条件(用于定位要更新的文档)。 3. 第二个参数是一个更新对象,包含更新运算符(如$set)和要修改的字段及新。 4. 可选地,第三个参数可以设置一些选项,如upsert。 另外,引用[3]和[4]都提供了类似的更新操作说明。 现在,我们根据用户的问题,给出一个完整的回答,并生成相关问题。</think>### MongoDB 更新单条文档操作详解 在 MongoDB 中更新单条文档,推荐使用 `updateOne()` 方法,语法如下: ```javascript db.collection.updateOne( <filter>, // 筛选条件(必选) <update>, // 更新操作(必选) { upsert: <boolean>, // 无匹配时是否插入新文档(默认false) writeConcern: <document>, // 写关注级别 collation: <document>, // 排序规则 arrayFilters: [ <filter> ] // 数组元素筛选 } ) ``` #### 核心参数说明 1. **`<filter>`** 使用查询条件定位目标文档,例如: `{ _id: ObjectId("507f191e810c19729de860ea") }` `{ "status": "active", "age": { $gt: 18 } }` 2. **`<update>`** - **`$set`**:修改/新增字段(推荐) ```javascript { $set: { name: "张三", email: "zhangsan@example.com", "address.city": "北京" }} ``` - **`$unset`**:删除字段 `{ $unset: { "temp_field": "" } }` - **`$inc`**:数增减 `{ $inc: { view_count: 1 } }` - **数组操作符**: `$push`(添加元素) / `$pull`(删除元素) / `$addToSet`(去重添加) #### 操作示例 **场景**:更新 `users` 集合中 `_id=1001` 的文档 ```javascript db.users.updateOne( { _id: 1001 }, // 定位文档 { $set: { status: "vip", last_login: new Date() }, $inc: { login_count: 1 }, $unset: { promo_code: "" } }, { upsert: true } // 若无匹配则创建新文档 ) ``` #### 返回说明 执行后将返回结果对象: ```json { "acknowledged": true, "matchedCount": 1, // 匹配文档数 "modifiedCount": 1, // 修改文档数 "upsertedId": null // 若upsert插入则显示新ID } ``` > ⚠️ **重要注意事项** > 1. 未使用 `$set` 等操作符时,更新操作会**直接替换整个文档**(覆盖更新)[^4] > 2. 更新操作具有**原子性**,确保并发安全 > 3. 使用 `{ upsert: true }` 可实现 "存在则更新,不存在则插入" 的逻辑[^3]
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值