代码之家  ›  专栏  ›  技术社区  ›  JAN

$Lookup在4个集合之间,其中3个集合带有ObjectId,第4个集合是String,产生空数组

  •  1
  • JAN  · 技术社区  · 5 年前

    我正在4个集合之间进行$查找:

    Client.aggregate(
          [
            {
              $lookup: {
                from: "clientboughtleads",
                localField: "_id",
                foreignField: "Client", // Client is "ObjectId"
                as: "ClientLeads"
              }
            },
            {
              $lookup: {
                from: "clientprofiles",
                localField: "_id",
                foreignField: "client", // client is "ObjectId"
                as: "ClientProfile"
              }
            },
    
            {
              $addFields: {
                TotalPurchasedLeads: {
                  $size: "$ClientLeads"
                }
              }
            },
    
            {
              $lookup: {
                from: "clientscreditloggers",
                localField: "_id",
                foreignField: "ClientId", // ClientId is "String"
                as: "ClientsCreditLoggers"
              }
            },
            {
              $project: {
                ClientId: "$_id",
                RegistrationDate: "$date",
                TotalPurchasedLeads: 1,
                PurchasedLeadsWorth: {
                  $multiply: [LEAD_PRICE, "$TotalPurchasedLeads"]
                },
                ClientType: "$ClientProfile.ClientType",
                ClientsCreditLoggers: "$ClientsCreditLoggers" // This one always empty
                // IncomeFromClient: { $sum: "$ClientsCreditLoggers.AmountBought" }
              }
            }
          ]
    
    1. 收藏 Client 有一个ObjectId,

    2. 收藏 clientboughtleads 也有一个ObjectId,

    3. 收藏 clientprofiles 同样地。

    4. 收藏 clientscreditloggers 有一个 ClientId 作为一根弦

    当我把这四个一起查找时,数组 ClientsCreditLoggers 是空的。

    我们怎么能同时$lookup 客户端CreditLoggers 和其他人一起收藏?

    1 回复  |  直到 5 年前
        1
  •  1
  •   mickl    5 年前

    你需要更换你的第三个 $lookup 低于1( custom pipeline )使用 $toObjectId 转换 String 身份证号码:

    {
          $lookup: {
            from: "clientscreditloggers",
            let: { local_id: "$_id" },
            pipeline: [ { $match: { $expr: { $eq: [ { $toObjectId: "$ClientId" }, "$$local_id" ] } } } ],
            as: "ClientsCreditLoggers"
        }
     }