MongoDB中数组中嵌入文档的$replaceRoot

MongoDB中数组中嵌入文档的$replaceRoot,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我对MongoDB是相当陌生的,我遇到了一个问题,我需要以我需要的方式输出文档 文档架构 { 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" } } ] } 想要的输出

我对MongoDB是相当陌生的,我遇到了一个问题,我需要以我需要的方式输出文档

文档架构

{
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"
    },
  ...
  ]
  }
i、 e:使引号字段成为另一个数组的根,而不是整个文档的根

谢谢。

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

差不多

db.col.aggregate([
  {
    "$addFields": {
      "other": {
        "$map": {
          "input": "$other",
          "as": "res",
          "in": {
            "text": "$$res.text"
          }
        }
      }
    }
  }
])
您可以轻松地在客户端代码中执行类似的操作。

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

查询是:

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

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