【问题标题】:MongoDB aggregation project the specific fields from lookupMongoDB 聚合项目来自查找的特定字段
【发布时间】:2021-03-06 04:37:16
【问题描述】:

这个例子在https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#use-lookup-with-mergeobjects之后

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

db.items.insert([
  { "_id" : 1, "item" : "almonds", description: "almond clusters", "instock" : 120 },
  { "_id" : 2, "item" : "bread", description: "raisin and nut bread", "instock" : 80 },
  { "_id" : 3, "item" : "pecans", description: "candied pecans", "instock" : 60 }
])

聚合:

db.orders.aggregate([
   {
      $lookup: {
         from: "items",
         localField: "item",    // field in the orders collection
         foreignField: "item",  // field in the items collection
         as: "fromItems"
      }
   },
   {
      $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }
   },
   { $project: { fromItems: 0 } }
])

结果:

{ "_id" : 1, "item" : "almonds", "description" : "almond clusters", "instock" : 120, "price" : 12, "quantity" : 2 }
{ "_id" : 2, "item" : "pecans", "description" : "candied pecans", "instock" : 60, "price" : 20, "quantity" : 1 }

问题:如何修改聚合以投影特定字段?例如仅限项目“_id”、“item”和“description”:

{ "_id" : 1, "item" : "almonds", "description" : "almond clusters" }
{ "_id" : 2, "item" : "pecans", "description" : "candied pecans" }

【问题讨论】:

  • 你所做的是正确的,mongoplayground.net/p/qhpWsmPKwVl。只需要投影想要的字段
  • @varman 谢谢,其实我的情况是这样的,mongoplayground.net/p/T96ijiGvZb5,我用orders.itemId来引用items._id,无法投影描述。
  • 问题是您在订单集合中的 itemId si 字符串,同时 _id 是项目集合中的数字。 @minsky 给你的答案是正确的。

标签: mongodb aggregation-framework


【解决方案1】:

你得到一个空数组,因为 $lookup 捕捉到任何东西。

  • 匹配类型
  • $addFields 转换

PLAYGROUND

这应该是第一阶段:

      {
        $addFields: {
          itemId: {
            $convert: {
              input: "$itemId",
              to: "int"
            }
          }
        }
      },

如果您愿意,无需添加舞台

  • 您也可以删除addFields 并使用$lookup+let。

以这种方式修改查找:

 {
    $lookup: {
      from: "items",
      let: {
        itemId: {
          $convert: {
            input: "$itemId",
            to: "int"
          }
        }
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$_id",
                "$$itemId"
              ]
            }
          }
        }
      ],
      /** field in the items collection*/
      as: "fromItems"
    }
  }

PLAYGROUND2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多