【发布时间】: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