我有以下文档 struct ,其中包含一个votes的数组:

    { _id: ObjectId("6350e2c1a15e0e656f4a7472"),
      category: 'business',
      votes: 
       [ { voteType: 'like',
           userId: ObjectId("62314007da34df3f32f7cfc0") },
         { voteType: 'like',
           userId: ObjectId("6356b5cbe2272ebf628451b") } ] }

我想要实现的是,在保留原始文件的同时,为每一份文件添加voteType = like票之和,例如:

    [ [{ _id: ObjectId("6350e2c1a15e0e656f4a7472"),
          category: 'business',
          votes: 
           [ { voteType: 'like',
               userId: ObjectId("62314007da34df3f32f7cfc0") },
             { voteType: 'like',
               userId: ObjectId("6356b5cbe2272ebf628451b") } ] }, {sum: 2, voteType: "like"} ], ...]

目前,我找到的唯一解决办法是通过聚合,尽管我无法设法在结果中保留原始文档:

     db.getCollection('MyDocument') .aggregate([   {
            $unwind: "$votes"   },   {
            $match: {
              "votes.voteType": "like",
            }   },   {
            $group: {
              _id: {
                name: "$_id",
                type: "$votes.voteType"
              },
              count: {
                $sum: 1
              }
            }   },
          { $sort : { "count" : -1 } },    {$limit : 5}
        ])

这给了我:

    { _id: { name: ObjectId("635004f1b96e494947caaa5e"), type: 'like' },
      count: 3 }
    { _id: { name: ObjectId("63500456b96e494947cbd448"), type: 'like' },
      count: 3 }
    { _id: { name: ObjectId("63500353b6c7eb0a01df268e"), type: 'like' },
      count: 2 }
    { _id: { name: ObjectId("634e315bb7d17339f8077c39"), type: 'like' },
      count: 1 }

推荐答案

您可以这样做:

  • $cond$isArray-判断votes属性是否为数组类型.
  • $filter-根据voteType属性筛选votes.
  • $size-获取已过滤数组的大小.
db.collection.aggregate([
  {
    "$set": {
      "count": {
        "$cond": {
          "if": {
            "$isArray": "$votes"
          },
          "then": {
            "$size": {
              "$filter": {
                "input": "$votes",
                "cond": {
                  "$eq": [
                    "$$this.voteType",
                    "like"
                  ]
                }
              }
            }
          },
          "else": 0
        }
      }
    }
  }
])

Working example

Mongodb相关问答推荐

MongoDB $lookup 查找字段值数组

DB 中的引用对象在 GraphQL 查询中返回 null

$group 和 sum + 添加所有大于

使用 $addFields 将字段添加到 $lookup 结果中的每个项目

用Golang减go mongodb中的两个字段

从嵌套数组中 id 匹配的另一个集合中获取所有字段

mongodb中集合的最大大小是多少

查找对象是否在预保存钩子mongoose中更改

在 mongoDB 中存储 java 8 LocalDate

删除嵌套文档数组中的嵌入文档

如何在mongo中插入带有日期的文档?

嵌套在文档数组中的mongodb展开数组

有没有办法将python对象直接存储在mongoDB中而不序列化它们

MongoDB $or 查询

带有 jQ​​uery Ajax/JSON 前端的 MongoDB 或 CouchDB 中间件

直接从 URL 查询字符串提供的 mongo 查询有多危险?

Mongo Schema-less集合和 C#

MongoDB备份计划

我在更新中对 $set 和 $inc 做错了什么

如何使用 Spring 的 MongoTemplate 和 Query 类检索字段子集?