nodejs mongodb 聚合无法正常工作

nodejs mongodb aggregation not working properly

我有这种MongoDBcollection

{
  "uploaded_video": [
    {
      "_id": "622a03e66d59f72b72358069",
      "user_id": "Ec3FNhk45Lh1xk92cO9eoXDiWEk2",
      "uploaded_video": {
        "_id": "622a0616242e5b2e65e8b3b4",
        "video_description": "test",
        "created_At": "2022-03-10T14:05:29.000Z",
        "recordedVideo": false,
        "thumbnailCreated": true
      },
      "activityType": "uploaded_video"
    }
  ],
  "comment_video": [
    {
      "_id": "622a03e66d59f72b72358069",
      "user_id": "Ec3FNhk45Lh1xk92cO9eoXDiWEk2",
      "comment_video": {
        "_id": "622a0616242e5b2e65e8b3b4",
        "video_description": "test",
        "created_At": "2022-03-10T14:05:29.000Z",
        "recordedVideo": false,
        "thumbnailCreated": true
      },
      "activityType": "comment_video"
    }
  ],
  "like_video": [
    {
      "_id": "622a03e66d59f72b72358069",
      "user_id": "Ec3FNhk45Lh1xk92cO9eoXDiWEk2",
      "like_video": {
        "_id": "622a0616242e5b2e65e8b3b4",
        "video_description": "test",
        "created_At": "2022-03-10T14:05:29.000Z",
        "recordedVideo": false,
        "thumbnailCreated": true
      },
      "activityType": "like_video"
    }
  ]
}

我想要一个字段里面给出的所有字段数据,我已经尽力了但是没有得到任何解决方案,希望有人能做到这一点,请解决这个问题以聚合,因为我会在后面添加一些条件聚合,我想使用聚合并想要下面的格式。

    {
  "all_data": [
    {
      "_id": "622a03e66d59f72b72358069",
      "user_id": "Ec3FNhk45Lh1xk92cO9eoXDiWEk2",
      "uploaded_video": {
        "_id": "622a0616242e5b2e65e8b3b4",
        "video_description": "test",
        "created_At": "2022-03-10T14:05:29.000Z",
        "recordedVideo": false,
        "thumbnailCreated": true
      },
      "activityType": "uploaded_video"
    }
    {
      "_id": "622a03e66d59f72b72358069",
      "user_id": "Ec3FNhk45Lh1xk92cO9eoXDiWEk2",
      "comment_video": {
        "_id": "622a0616242e5b2e65e8b3b4",
        "video_description": "test",
        "created_At": "2022-03-10T14:05:29.000Z",
        "recordedVideo": false,
        "thumbnailCreated": true
      },
      "activityType": "comment_video"
    },
    {
      "_id": "622a03e66d59f72b72358069",
      "user_id": "Ec3FNhk45Lh1xk92cO9eoXDiWEk2",
      "like_video": {
        "_id": "622a0616242e5b2e65e8b3b4",
        "video_description": "test",
        "created_At": "2022-03-10T14:05:29.000Z",
        "recordedVideo": false,
        "thumbnailCreated": true
      },
      "activityType": "like_video"
    }
  ]
}

你能试试吗:

db.collection.aggregate([
  {
    $project: {
      allData: {
        uploaded_video: "$uploaded_video",
        comment_video: "$comment_video",
        like_video: "$like_video"
      }
    }
  },
])
db.collection.aggregate([
  {
    $project: {
      allData: {
        $concatArrays: [
          "$uploaded_video",
          "$comment_video",
          "$like_video"
        ]
      }
    }
  }
])

mongoplayground

您可以使用 $addFields$concatArrays 来获得您需要的格式。您可以获得演示代码here。希望这对你有所帮助。