I have document in mongoDb database with sub categories and need select sub categories into main object, but can't find way how to do it in MongoDb way Current document:
{
"title": "main title",
"subCategories": [
{
"title": "sub title 1",
},
{
"title": "sub main title 2",
},
{
"title": "sub main title 3",
},
]
}
Expecting result:
{[
{
"title": "main title"
},
{
"title": "sub title 1",
},
{
"title": "sub main title 2",
},
{
"title": "sub main title 3",
}
]}
CodePudding user response:
As mentioned in the comment, you need to have a key-value pair in the object. Otherwise, it's invalid. To get all things in an array under a single key, try this:
db.collection.aggregate([
{
"$project": {
"subCategories": {
"$concatArrays": [
[
{
title: {
"$getField": {
"field": "title",
"input": "$$ROOT"
}
}
}
],
"$subCategories",
]
}
}
}
])
Here's the playground link.