在MongoDB聚合中使用$replaceRoot。$replaceRoot用指定的文档替换输入文档。该操作将替换输入文档中的所有现有字段,包括_id字段。让我们用文档创建一个集合–
> db.demo733.insertOne( ... { ... "SubjectDetails": ... [ ... { ... SubjectName:"MongoDB", ... "Marks":85 ... }, ... { ... SubjectName:"MySQL", ... "Marks":90 ... }, ... { ... SubjectName:"PL/SQL", ... "Marks":98 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eac6e6156e85a39df5f6342") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo733.find();
这将生成以下输出−
{ "_id" : ObjectId("5eac6e6156e85a39df5f6342"), "SubjectDetails" : [ { "SubjectName" : "MongoDB", "Marks" : 85 }, { "SubjectName" : "MySQL", "Marks" : 90 }, { "SubjectName" : "PL/SQL", "Marks" : 98 } ] }
下面是一个查询,用于将嵌入的文档数组上移到父级并使用聚合管道-更改键/值
> db.demo733.aggregate([ ... { ... $replaceRoot: { ... newRoot: { ... $mergeObjects: [ .. . { _id: "$_id" }, ... { $arrayToObject: { $map: { input: "$SubjectDetails", in: [ "$$this.SubjectName", "$$this.Marks" ] } } } ... ] ... } ... } ... } ... ]).pretty()
这将产生以下输出−
{ "_id" : ObjectId("5eac6e6156e85a39df5f6342"), "MongoDB" : 85, "MySQL" : 90, "PL/SQL" : 98 }