首页 > 解决方案 > 如何通过字段 user_id 进行分组并从 mongoDB 中的另一个表填充

问题描述

我是 mongoDB 的新手,在获得所需结果方面遇到问题。

MongoDB v:4.2.0

我只想要格式的数据(类似这样的):

{
    array[ array[{ bot, user_response , user_id }] ] where client_id = '1234'
}

对输出的更多解释:我需要每个为 client_id = 1234 提交聊天的唯一用户的聊天详细信息数组

对于每个唯一的 user_id,我需要一个包含所有匹配项的数组(例如在 group by 中)。还从 chatSchema 表中填充机器人。

    chatSchema {
{
    _id: {
        type : String,
        unique : true,
        required : true
    },
    content: {
      type: Array,
      required: true,
      trim: true,
    },
    response: {
      type: Array
    },
  }
}

我的表结构如下:

    {
    "_id": {
        "$oid": "600efa3592bd1f61be91afc5"
    },
    "bot": "4",
    "user_response": {
        "type": "button",
        "text": "Restart",
        "value": "restart",
        "id": "restart"
    },
    "user_id": "a34ba8505477",
    "client_id": "1234",
    "createdAt": {
        "$date": "2021-01-25T17:04:53.083Z"
    },
    "updatedAt": {
        "$date": "2021-01-25T17:04:53.083Z"
    },
    "__v": 0
}

{
    "_id": {
        "$oid": "600efa3a92bd1f61be91afc6"
    },
    "bot": "1",
    "user_response": {
        "type": "button",
        "text": "thanks",
        "value": "2",
        "id": "2"
    },
    "user_id": "8866b1863079",
    "client_id": "1234",
    "createdAt": {
        "$date": "2021-01-25T17:04:58.053Z"
    },
    "updatedAt": {
        "$date": "2021-01-25T17:04:58.053Z"
    },
    "__v": 0
}

{
    "_id": {
        "$oid": "600efa3d92bd1f61be91afc7"
    },
    "bot": "2",
    "user_response": {
        "type": "button",
        "text": "Girl",
        "value": "4",
        "id": "4"
    },
    "user_id": "8866b1863079",
    "client_id": "1234",
    "createdAt": {
        "$date": "2021-01-25T17:05:01.282Z"
    },
    "updatedAt": {
        "$date": "2021-01-25T17:05:01.282Z"
    },
    "__v": 0
}

标签: mongodbmongoosemongodb-queryaggregation-frameworkaggregate

解决方案


推荐阅读