【问题标题】:$replaceRoot of embedded document inside an array in MongoDB$replaceRoot 在 MongoDB 中的数组内嵌入文档
【发布时间】:2019-12-05 16:57:39
【问题描述】:

我是 MongoDB 的新手,我遇到了 $replaceRoot(aggregation),我需要以我需要的方式输出文档。

文档架构

{
name: "Apple",
image: "",
is_fruit: true,
other: [
  {
    url: "",
    quotes: { // saved as ObjectId and is then lookedup or populated
    text: "An apple a day keeps the doctor away"
  }
}
]
}

想要的输出

{
  name: "Apple",
  image: "",
  is_fruit: true,
  other: [
    {
      text: "An apple a day keeps the doctor away"
    },
  ...
  ]
  }

即:将引号字段作为另一个数组的根而不是整个文档的根。

谢谢。

【问题讨论】:

  • 我真的不明白你在这里想要达到的目标。您是否试图限制数组内返回字段的数量?或者“url”和“quotes”字段在哪里?

标签: mongodb aggregation-framework


【解决方案1】:

嵌入式数组没有$replaceRoot 之类的,但您可以使用$map 将数组转换为新格式来实现类似的效果。

类似

db.col.aggregate([
  {
    "$addFields": {
      "other": {
        "$map": {
          "input": "$other",
          "as": "res",
          "in": {
            "text": "$$res.text"
          }
        }
      }
    }
  }
])

您可以轻松地在客户端代码中执行类似的操作。

【讨论】:

    【解决方案2】:

    通过使用 $replaceRoot(aggregation) 这里是输出。 P.S:我使用的集合名称是“demoStack”,将其替换为您的特定集合。

    查询是:

    db.demoStack.aggregate([
    { $replaceRoot: { newRoot: { $mergeObjects: [ 
        {name:"$name"},
        { image: "$image" },
        {is_fruit:"$is_fruit"},
        {other:"$other.quotes"}        
        ] } } } ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-30
      • 2018-05-09
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2021-08-07
      相关资源
      最近更新 更多