mongodb Mongo $lookup查询获取别名为空

camsedfj  于 2023-03-01  发布在  Go
关注(0)|答案(2)|浏览(151)
db.ticket.aggregate([
  {
    $lookup: {
      from: "crmorder",
      localField: "subOrderId",
      foreignField: "currentStatus",
      as: "comments"
    }
  }
])

结果备注栏中为什么会出现空白?

oknwwptz

oknwwptz1#

还有一个名为crmorder的表
票证表中必须有- subOrderId字段
在crmorder表中必须有- currentStatus字段
以及票据表子订单ID字段== crmorder表当前状态字段
以下是示例片段:

db.orders.insert([
   { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
   { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
   { "_id" : 3  }
])

db.inventory.insert([
   { "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 },
   { "_id" : 2, "sku" : "bread", description: "product 2", "instock" : 80 },
   { "_id" : 3, "sku" : "cashews", description: "product 3", "instock" : 60 },
   { "_id" : 4, "sku" : "pecans", description: "product 4", "instock" : 70 },
   { "_id" : 5, "sku": null, description: "Incomplete" },
   { "_id" : 6 }
])

db.orders.aggregate([
   {
     $lookup:
       {
         from: "inventory",
         localField: "item",
         foreignField: "sku",
         as: "inventory_docs"
       }
  }
])
iyfjxgzm

iyfjxgzm2#

Try adding a pipeline under your $lookup

sample:

db.orders.aggregate([
    {
      $lookup: {
          from: "inventory",
          localField: "item",
          foreignField: "sku",
          pipeline: [
            {
              $project: {
                _id: 1,
                sku: 1,
                description: 1, 
              },
            },
          ],
          as: "inventory_docs",
      },
    }
  ])

相关问题