Mongodb-如何转换数组中的嵌套对象
我将数据文件从外部源导入数据库。此数据在嵌套对象的数组中具有嵌套对象。例如:Mongodb-如何转换数组中的嵌套对象,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我将数据文件从外部源导入数据库。此数据在嵌套对象的数组中具有嵌套对象。例如: { "_id" : ObjectId("59de680a8a042e19b4ac4895"), "_embedded" : { "identification" : [ { "name" : "Bill Brasky", "id" : "brasky9z5", "type" : "Client" },
{
"_id" : ObjectId("59de680a8a042e19b4ac4895"),
"_embedded" : {
"identification" : [
{
"name" : "Bill Brasky",
"id" : "brasky9z5",
"type" : "Client"
},
{
"name" : "Merle Haggard",
"id" : "mh2017",
"type" : "Vendor"
},
{
"name" : "Captain American",
"id" : "1a1a1a1",
"type" : "Client"
}
]
}}
我希望使用聚合操作仅查看“id”和“type”值。如果没有数组或嵌套文档,我知道如何使用聚合返回结果
db.users.aggregate(
{ $project : {
_id : 0 ,
id : 1 ,
type : 1
}})
我想我需要使用$REWIND,但我的大脑却在运转。如何更新聚合操作以投影所需字段?使用
$map
转换嵌入数组
差不多
db.users.aggregate({
"$addFields": {
"_embedded.identification": {
"$map": {
"input": "$_embedded.identification",
"as": "result",
"in": {
"id": "$$result.id",
"type": "$$result.type"
}
}
}
}
})
使用
$map
转换嵌入式阵列
差不多
db.users.aggregate({
"$addFields": {
"_embedded.identification": {
"$map": {
"input": "$_embedded.identification",
"as": "result",
"in": {
"id": "$$result.id",
"type": "$$result.type"
}
}
}
}
})
太好了,谢谢@Veeram。是否有一种简单的方法可以在单个记录中获得输出,而不仅仅是作为添加的字段。这将是必要的,因为我将使用$out导出到另一个表中的新文档。(这部分我已经弄明白了)不客气。在
$out
阶段之前添加{$unwind:“$\u embedded.identification”}
这太棒了,谢谢@Veeram。是否有一种简单的方法可以在单个记录中获得输出,而不仅仅是作为添加的字段。这将是必要的,因为我将使用$out导出到另一个表中的新文档。(这部分我已经弄明白了)不客气。在$out
阶段之前添加{$unwind:“$\u embedded.identification”}