sql >> Base de Datos >  >> NoSQL >> MongoDB

Mongoose une dos colecciones y obtiene datos referenciados en dos propiedades

Puedes probar,

  • $addFields para hacer una matriz única llamada userIds formar ambas matrices followers y followings , $setUnion para obtener identificaciones únicas,
  • $lookup con colección de usuarios
  • $project para mostrar campos,
    • followers obtener fullName, $map para iterar el ciclo de followers y obtenga el nombre de followerId de la matriz de usuarios usando $reduce y $cond
    • followings obtener fullName, $mapa para iterar el bucle de followings y obtenga el nombre de followingId de la matriz de usuarios usando $reduce y $cond
db.followings.aggregate([
  {
    $addFields: {
      userIds: {
        $setUnion: [
          {
            $map: {
              input: "$followers",
              in: "$$this.followerId"
            }
          },
          {
            $map: {
              input: "$followings",
              in: "$$this.followingId"
            }
          }
        ]
      }
    }
  },
  {
    $lookup: {
      from: "users",
      localField: "userIds",
      foreignField: "_id",
      as: "users"
    }
  },
  {
    $project: {
      userId: 1,
      followers: {
        $map: {
          input: "$followers",
          as: "f",
          in: {
            $mergeObjects: [
              "$$f",
              {
                fullName: {
                  $reduce: {
                    input: "$users",
                    initialValue: "",
                    in: {
                      $cond: [
                        { $eq: ["$$this._id", "$$f.followerId"] },
                        "$$this.fullName",
                        "$$value"
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      },
      followings: {
        $map: {
          input: "$followings",
          as: "f",
          in: {
            $mergeObjects: [
              "$$f",
              {
                fullName: {
                  $reduce: {
                    input: "$users",
                    initialValue: "",
                    in: {
                      $cond: [
                        { $eq: ["$$this._id", "$$f.followingId"] },
                        "$$this.fullName",
                        "$$value"
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

Patio de juegos