美文网首页
mongod关联表完整篇(解决objectid类型不匹配难度)

mongod关联表完整篇(解决objectid类型不匹配难度)

作者: 塔塔七 | 来源:发表于2021-03-30 15:28 被阅读0次
    findById: async (db, id) => {
        return db.aggregate([
          {
            $lookup: {
              from: "collections",
              let: { jobId: "$_id" },
              pipeline: [
                { $addFields: { productId: { $toObjectId: "$goodsid" } } },
                { $match: { $expr: { $eq: ["$productId", "$$jobId"] } } },
              ],
              as: "product_collection",
            },
          },
          { $match: { $expr: { $eq: [{ $toString: "$_id" }, id] } } },
        ]);
      },
    

    根据从表过滤主表数据

    findCollectByUid: async (db, uid) => {
        return db.aggregate([
          {
            $lookup: {
              from: "collections",
              let: { jobId: "$_id" },
              pipeline: [
                { $addFields: { ProductId: { $toObjectId: "$goodsid" } } },
                { $match: { $expr: { $eq: ["$ProductId", "$$jobId"] }, uid: uid } },管道内过滤
              ],
              as: "collect",
            },
          },
          { $match: { "collect.0.uid": uid } },  // {$match:{"主表字段":"条件","collect.从表字段":"条件"} }])
    
        ]);
      },
    

    相关文章

      网友评论

          本文标题:mongod关联表完整篇(解决objectid类型不匹配难度)

          本文链接:https://www.haomeiwen.com/subject/adlghltx.html