mongodb 使用 $reduce 将值推入数组

Ifa*_*uki 2 mongodb

我有这样的文档结构:

_id: 123,
posts: [
   {
      _id: 234,
      likesUser: [345, 456, 567, 678]
   }
]
Run Code Online (Sandbox Code Playgroud)

我想在这里使用$reduce,所以我的预期输出应该如下所示:

   output: {
      likes: [23, 31, 12, 32],  //each element is the size of the "likesUser" array
      ids: ["14312", "2342", "2312", "235234"]  //each element is the "_id" in the posts array
   }
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这样的:

  let result = await Post.aggregate([
    {
      $match: {
        _id: USER
      }
    },
    {
      $project: {
        posts: {
          $reduce: {
            input: "$posts",
            initialValue: { likes: [], ids: [] },
            in: {
              likes: {
                $push: { $size: "$$this.likesUser" }
              },
              ids: {
                $push: "$$this._id"
              }
            }
          }
        }
      }
    }
  ]);
Run Code Online (Sandbox Code Playgroud)

在我的前端我使用chart.js。yAxsis 是喜欢的,xAxsis 是 ID 的。因此,对于数组中的每个元素,posts我需要 的长度likesUser_id 但它确实有效。有人知道如何实现这一目标吗?

Tom*_*ert 6

你已经非常接近了,你只是在你的$reduce中有一个小语法错误,试试这个:

let result = await Post.aggregate([
    {
        $match: {
            _id: USER
        }
    },
    {
        $project: {
            posts: {
                $reduce: {
                    input: "$posts",
                    initialValue: {likes: [], ids: []},
                    in: {
                        likes: {
                            $concatArrays: ["$$value.likes", [{$size: "$$this.likesUser"}]]
                        },
                        ids: {
                            $concatArrays: ["$$value.ids", ["$$this._id"]]
                        }
                    }
                }
            }
        }
    }
]);
Run Code Online (Sandbox Code Playgroud)