英文:
How to collect array objects' values to separate the array in MongoDB Aggregation Framework?
问题
这是收藏内容的示例:
博客作者
[
{
_id: ObjectId(...),
posts: [
{
"platform": "instagram"
},
{
"platform": "tiktok"
},
],
full_name: "John Doe",
},
{
_id: ObjectId(...),
posts: [
{
"platform": "youtube"
},
{
"platform": "tiktok"
},
],
full_name: "Mamed Mamedov"
}
]
聚合的结果,我想要得到类似于这样的东西:
[
{
_id: ObjectId(...),
platforms: ["instagram", "tiktok"],
full_name: "John Doe",
},
{
_id: ObjectId(...),
platforms: ["youtube", "tiktok"],
full_name: "Mamed Mamedov"
}
]
(从 posts
字段的平台列表)
英文:
Here is the example of collection content:
bloggers
[
{
_id: ObjectId(...),
posts: [
{
"platform": "instagram"
},
{
"platform": "tiktok"
},
],
full_name: "John Doe",
},
{
_id: ObjectId(...),
posts: [
{
"platform": "youtube"
},
{
"platform": "tiktok"
},
],
full_name: "Mamed Mamedov"
}
]
And as a result of the aggregation, I wanna get something like this:
[
{
_id: ObjectId(...),
platforms: ["instagram", "tiktok"],
full_name: "John Doe",
},
{
_id: ObjectId(...),
platforms: ["youtube", "tiktok],
full_name: "Mamed Mamedov"
}
]
(List of the platforms from posts
field)
For now, I even not sure, that there is some ready-to-use method in mongodb.
答案1
得分: 0
你可以使用$reduce
轻松完成这个操作:
db.collection.aggregate([
{
"$project": {
"full_name": 1,
"platforms": {
"$reduce": {
"input": "$posts",
"initialValue": [],
"in": {
"$concatArrays": [
"$$value",
[
"$$this.platform"
]
]
}
}
}
}
}
])
英文:
You can do this easy with $reduce:
db.collection.aggregate([
{
"$project": {
"full_name":1,
"platforms": {
"$reduce": {
"input": "$posts",
"initialValue": [],
in: {
$concatArrays: [
"$$value",
[
"$$this.platform"
]
]
}
}
}
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论