English 中文(简体)
对蒙戈巴的深层物体进行勘测
原标题:Applying lookup in deeply nested array of objects in MongoDB
The bounty expires in 7 hours. Answers to this question are eligible for a +50 reputation bounty. arpandhakal is looking for a canonical answer.

我有点问,有人对Ids提出反对的深层文件。 我想从物体Ids中提取每个推进剂的细节。 询问:

      const result = await this.ticketsv2Model
        .aggregate([
          {
            $match: query,
          },
          {
            $sort: {
              createdAt: -1,
            },
          },
          ...generateLookupStage( issues ,  issueId , [ _id ,  name ]),
          ...generateLookupStage( subissues ,  subIssueId , [ _id ,  name ]),
          ...generateLookupStage( tickettypes ,  typeId , [ _id ,  name ]),
          ...generateLookupStage( statustypes ,  statusId , [ _id ,  name ]),
          ...generateLookupStage( departments ,  assignedDepartment , [
             _id ,
             name ,
          ]),
          ...generateLookupStage( users ,  assignedTo , [
             _id ,
             extension ,
             firstName ,
             lastName ,
          ]),
          ...generateLookupStage( users ,  openedBy , [
             _id ,
             extension ,
             firstName ,
             lastName ,
          ]),

          {
            $unwind:  $ticketLogs ,
          },
          ...generateLookupStage( users ,  ticketLogs.userId , [
             _id ,
             firstName ,
             lastName ,
             extension ,
          ]),
          ...generateLookupStage( statustypes ,  ticketLogs.statusId , [
             _id ,
             name ,
          ]),

          ...generateLookupStage(
             departments ,
             ticketLogs.assignedDepartment ,
            [ _id ,  name ,  number ],
          ),
          ...generateLookupStage( users ,  ticketLogs.assignedTo , [
             _id ,
             firstName ,
             lastName ,
             extension ,
          ]),
          {
            $group: {
              _id:  $_id ,
              issueId: { $first:  $issueId  },
              subIssueId: { $first:  $subIssueId  },
              typeId: { $first:  $typeId  },
              ticketId: { $first:  $ticketId  },
              resolutionTime: { $first:  $resolutionTime  },
              clientInfo: { $first:  $clientInfo  },
              statusId: { $first:  $statusId  },
              openedBy: { $first:  $openedBy  },
              remarks: { $first:  $remarks  },
              assignedTo: { $first:  $assignedTo  },
              assignedDepartment: { $first:  $assignedDepartment  },
              ticketLogs: {
                $push: {
                  chatId:  $ticketLogs.chatId ,
                  recordingId:  $ticketLogs.recordingId ,
                  voiceMailRecordingId:  $ticketLogs.voiceMailRecordingId ,
                  remarks:  $ticketLogs.remarks ,
                  statusId:  $ticketLogs.statusId ,
                  userId:  $ticketLogs.userId ,
                  assignedTo:  $ticketLogs.assignedTo ,
                  assignedDepartment:  $ticketLogs.assignedDepartment ,
                  comments:  $ticketLogs.comments ,
                },
              },
            },
          },
          {
            $project: {
              createdAt: 1,
              issueId: 1,
              subIssueId: 1,
              typeId: 1,
              clientInfo: 1,
              statusId: 1,
              remarks: 1,
              assignedDepartment: 1,
              assignedTo: 1,
              ticketLogs: 1,
              ticketId: 1,
              openedBy: 1,
              _id: 1,
              action: {
                $switch: {
                  branches: [
                    {
                      case: {
                        $eq: [ $assignedTo._id , new Types.ObjectId(user)],
                      },
                      then:  update ,
                    },
                    {
                      case: {
                        $and: [
                          {
                            $in: [ $assignedDepartment._id , userDepartments],
                          },
                          { $eq: [{ $type:  $assignedTo._id  },  missing ] },
                        ],
                      },
                      then:  pick ,
                    },
                  ],
                  default:  view ,
                },
              },
            },
          },
        ])
        .exec();

产生忽略成分是一种习惯功能,可进行考量(来自当地和安插;因为,[或许你希望从文件中产生效应]。 我的机票文件:

{
  "_id": {
    "$oid": "65b2143e5b239b78bc756a68"
  },
  "issueId": {
    "$oid": "644e940200d3bd6ab311f1fb"
  },
  "subIssueId": {
    "$oid": "644e94b100d3bd6ab311f216"
  },
  "typeId": {
    "$oid": "65828ebea1726254da22e506"
  },
  "clientInfo": {
    "clientId": "1231235645123",
    "clientEmail": "[email protected]",
    "clientPhone": "12233",
    "clientName": "Arpan Dhakal",
    "clientImage": "linkto.image",
    "_id": {
      "$oid": "65b2143e5b239b78bc756a69"
    }
  },
  "statusId": {
    "$oid": "658294ca9777467f6777802e"
  },
  "remarks": "Custom remarks here",
  "assignedDepartment": {
    "$oid": "658294a2aa8146af8fe85b50"
  },
  "ticketLogs": [
    {
      "chatId": "658294a2aa8146af8fe85b50",
      "recordingId": "658294a2aa8146af8fe85b50",
      "voiceMailRecordingId": "658294a2aa8146af8fe85b50",
      "remarks": "Ticket Created",
      "statusId": {
        "$oid": "658294f1660cac3e3acda29a"
      },
      "userId": {
        "$oid": "65af5d2e08a356fd82718d64"
      },
      "assignedTo": null,
      "assignedDepartment": {
        "$oid": "658294a2aa8146af8fe85b50"
      },
      "_id": {
        "$oid": "65b2143e5b239b78bc756a6a"
      },
      "createdAt": {
        "$date": "2024-01-25T07:56:46.778Z"
      },
      "updatedAt": {
        "$date": "2024-01-25T07:56:46.778Z"
      },
      "comments": [
        {
          "comment": "hello world",
          "createdAt": {
            "$date": "2024-01-26T06:21:21.429Z"
          },
          "commentedBy": {
            "$oid": "65af5d2e08a356fd82718d64"
          },
          "_id": {
            "$oid": "65b34f61ec6cb747fc19f73a"
          }
        },
        {
          "comment": "hello world",
          "createdAt": {
            "$date": "2024-01-26T06:30:14.002Z"
          },
          "commentedBy": {
            "$oid": "65af5d2e08a356fd82718d64"
          },
          "_id": {
            "$oid": "65b35176cb2f23c9563c45f5"
          }
        },
        {
          "comment": "comment",
          "commentedBy": {
            "$oid": "644e06fc00d3bd6ab311d5fd"
          },
          "_id": {
            "$oid": "65e99131c599c2d633062497"
          },
          "createdAt": {
            "$date": "2024-03-07T10:04:33.007Z"
          },
          "updatedAt": {
            "$date": "2024-03-07T10:04:33.007Z"
          }
        }
      ]
    }
  ],
  "ticketId": "T-55NNXUBW",
  "openedBy": {
    "$oid": "644e06fc00d3bd6ab311d5fd"
  },
  "createdAt": {
    "$date": "2024-01-25T07:56:46.778Z"
  },
  "updatedAt": {
    "$date": "2024-03-07T10:04:33.007Z"
  },
  "__v": 0,
  "assignedTo": {
    "$oid": "644e06fc00d3bd6ab311d5fd"
  }
}

基本上,我的文件有机票记录仪,是机票记录仪文件的一系列物体。 每张票记录仪都有评论意见,这些评论是评论文件的一系列内容。 查询工作涉及打字用户、状况、部门每张票记录的细节。 现在,我想对每项评论的用户细节进行说明。 这些评论主张发表评论。 我想评论By显示评论的用户的信息。

问题回答

这里,您可如何修改您的聚合管道,以列入为每项评论收集用户详细信息的必要阶段:

  1. Add a $unwind stage for ticketLogs (which you already have).
  2. Add a $unwind stage for ticketLogs.comments to flatten this nested array.
  3. Use $lookup to fetch user details for each commentedBy field in the flattened comments array.
  4. $group by the ticketLog level to reconstruct the ticketLogs array with enriched comments.
  5. $group by the document level to reconstruct the original document structure with the enriched ticketLogs.

这里,这些额外阶段将如何看待你现有的管道:

// Existing stages...

{
  $unwind:  $ticketLogs  // You already have this stage.
},
{
  $unwind: {
    path:  $ticketLogs.comments ,
    preserveNullAndEmptyArrays: true // This ensures that ticketLogs without comments are still included
  }
},
...generateLookupStage( users ,  ticketLogs.comments.commentedBy , [ _id ,  firstName ,  lastName ,  extension ]),
{
  $group: {
    _id: {
      ticketLogId:  $ticketLogs._id , // Group by ticketLog ID
      rootId:  $_id  // Preserve the root document ID
    },
    ticketLog: { $first:  $ticketLogs  }, // Use $first since all entries in a group belong to the same ticketLog
    comments: { $push:  $ticketLogs.comments  } // Reconstruct the comments array
  }
},
{
  $group: {
    _id:  $_id.rootId , // Group by the original document ID
    ticketLogs: { $push: { $mergeObjects: [ $ticketLog , { comments:  $comments  }] } }, // Reconstruct the ticketLogs array with enriched comments
    root: { $first:  $$ROOT  } // Preserve the original document
  }
},
{
  $replaceRoot: {
    newRoot: {
      $mergeObjects: [ $root , { ticketLogs:  $ticketLogs  }] // Merge the enriched ticketLogs back into the original document
    }
  }
},

// Follow with your existing $group and $project stages...

这种办法将<条形状记录仪表>栏目阵列加以统一,以允许在<条码>上进行操作,然后将阵列重新调整至其原有封结构。 各位不妨根据您的实际数据和要求调整外地名称和结构。 此外,确保您的<代码>generateLookupS功能能够根据所提供的途径正确处理这些调查。





相关问题
Access DB Ref MongoDB

Whats the best way to access/query a DB Ref: UPDATE: users: name, groupref : {$ref:"groups",$id:"ObjectId ..." } } groups: name, topic, country,...,.. Assumption is that user belongs to only one ...

MongoDB nested sets

What re the best practices to store nested sets (like trees of comments) in MongoDB? I mean, every comment can have a parent comment and children-comments (answers). Storing them like this: { ...

MongoMapper and migrations

I m building a Rails application using MongoDB as the back-end and MongoMapper as the ORM tool. Suppose in version 1, I define the following model: class SomeModel include MongoMapper::Document ...

MongoDB takes long for indexing

I have the following setup: Mac Pro with 2 GB of RAM (yes, not that much) MongoDB 1.1.3 64-bit 8 million entries in a single collection index for one field (integer) wanted Calling .ensureIndex(...) ...

Storing and accessing large amounts of data

My application creates pieces of data that, in xml, would look like this: <resource url="someurl"> <term> <name>somename</name> <frequency>somenumber</...

热门标签