在MongoDB聚合管道中分解数组

问题描述

我想知道是否仍然可以在MongoDB聚合管道中对数组进行解构,从而使我的代码更加整洁。

例如,我有以下聚合管道。

await User.aggregate([
      { $match: { _id: userID } },{
        $project: { chatLogs: 1,username: 1,profilePicURL: 1 },},{ $unwind: "$chatLogs" },{
        $lookup: {
          from: "users",let: { recipientID: "$chatLogs.recipientID" },pipeline: [
            {
              $match: { $expr: { $eq: ["$_id","$$recipientID"] } },{ $project: { profilePicURL: 1 } },],as: "chatLogs.recipientID",]);

查询时会得到以下结果:

{
        "_id": "5f2ffb54eea9c2180a732afa","username": "joe","profilePicURL": "/images/profile/default_profile.png","chatLogs": {
            "recipientID": [
                {
                    "_id": "5f2faf5ad18a76073729f475","profilePicURL": "/images/profile/default_profile.png"
                }
            ],"chat": "5f30b6c3d117441c2abda1ba"
        }
    }

就我而言,由于“ recipientID”代表认的MongoDB ID,因此它将始终是唯一的。因此,我希望使用以下方法,其中所得的receiveID字段不再是无意义的数组

所需结果:

{
        "_id": "5f2ffb54eea9c2180a732afa","chatLogs": {
            "recipientID": {
                    "_id": "5f2faf5ad18a76073729f475","profilePicURL": "/images/profile/default_profile.png"
                }
            "chat": "5f30b6c3d117441c2abda1ba"
        }
    }

解决方法

您可以在最后一个管道中使用recipientID解构$unwind数组,

await User.aggregate([
      ... // your all pipelines

      // add this line
      { $unwind: "$chatLogs.recipientID" }
]);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...