如何从嵌套对象数组 mongodb 聚合创建单个对象数组?
How do I create a single array of object from nested array of obejcts mongodb aggregate?
我是 Mongodb 的新手,对聚合了解不多,如何将下面的对象更改为所需的单个对象数组。
[
{
id: "1",
title: "First Title",
des: "This is desc",
contents: [
{
id: "1",
title: "content-1 title",
des: "This is desc"
},
{
id: "2",
title: "Content-2 title",
des: "This is desc"
}
]
},
{
id: "2",
title: "Second Title is Here",
des: "This is desc",
contents: [
{
id: "1",
title: "content-1 title",
des: "This is desc"
},
{
id: "2",
title: "Content-2 title",
des: "This is desc"
}
]
}
]
我想要的单个阵列:
[
{
id: "1",
title: "First Title",
des: "This is desc"
},
{
id: "1",
title: "content-1 title",
des: "This is desc"
},
{
id: "2",
title: "Content-2 title",
des: "This is desc"
},
{
id: "2",
title: "Second Title is Here",
des: "This is desc"
},
{
id: "1",
title: "content-1 title",
des: "This is desc"
},
{
id: "2",
title: "Content-2 title",
des: "This is desc"
}
]
db.collection.aggregate([
{
$set: {
contents: {
$concatArrays: [
[
{
id: "$id",
title: "$title",
des: "$des"
}
],
"$contents"
]
}
}
},
{
$unwind: "$contents"
},
{
$replaceWith: "$contents"
}
])
我是 Mongodb 的新手,对聚合了解不多,如何将下面的对象更改为所需的单个对象数组。
[
{
id: "1",
title: "First Title",
des: "This is desc",
contents: [
{
id: "1",
title: "content-1 title",
des: "This is desc"
},
{
id: "2",
title: "Content-2 title",
des: "This is desc"
}
]
},
{
id: "2",
title: "Second Title is Here",
des: "This is desc",
contents: [
{
id: "1",
title: "content-1 title",
des: "This is desc"
},
{
id: "2",
title: "Content-2 title",
des: "This is desc"
}
]
}
]
我想要的单个阵列:
[
{
id: "1",
title: "First Title",
des: "This is desc"
},
{
id: "1",
title: "content-1 title",
des: "This is desc"
},
{
id: "2",
title: "Content-2 title",
des: "This is desc"
},
{
id: "2",
title: "Second Title is Here",
des: "This is desc"
},
{
id: "1",
title: "content-1 title",
des: "This is desc"
},
{
id: "2",
title: "Content-2 title",
des: "This is desc"
}
]
db.collection.aggregate([
{
$set: {
contents: {
$concatArrays: [
[
{
id: "$id",
title: "$title",
des: "$des"
}
],
"$contents"
]
}
}
},
{
$unwind: "$contents"
},
{
$replaceWith: "$contents"
}
])