MongoDB查询中$replaceRoot的正确使用



我得到了一个MongoDB实例,其中有3个表以以下方式构建:

  • 公司{_id, [productIds], foo,酒吧,…}
  • Product {_id, productCategoryId, foo, bar,…}
  • ProductCategory {_id, foo, bar,…}

我想要一个返回带有附加字段的所有公司数据的结果。它应该包含所有产品数据(因此基本上是productid上的连接)。每个产品都应与其类别相关联。

我得到了以下查询:

db.companyentities.aggregate([
{
$unwind: "$productIds"
},
{
$lookup: {
as: "products",
foreignField: "_id",
from: "productentities",
localField: "productIds"
}
},
{
$unwind: "$products"
},
{
$lookup: {
as: "products.productCategory",
foreignField: "_id",
from: "productcategoryentities",
localField: "products.productCategoryId"
}
},
{
$unwind: "$products.productCategory"
},
{
$group: {
_id: "$_id",
products: {
$push: "$products"
},
detail: {
$first: "$$ROOT"
}
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{products: "$products"},
{detail: "$detail"}
],
}
}
}
])

我得到了正确的连接,问题是结果的格式为{company id, details: {companyData}, products {productData}}。

我想要的是数据库中的公司数据,但要增加一个包含产品数据的列。

我如何做到这一点?我猜我在$replaceRoot部分做错了什么。

提前感谢您的建议:)

@Joe的回答是正确的,谢谢:)

不要使用{detail: "$detail"},而是使用"$detail">

最新更新