Here is an array which I got after a long aggregation.
"stages": [
[
{
"id": "58a6678bc27c331884b60930",
"description": "Lorem ipsum dolor sit amet...",
"somevalue": 0,
"user": "589cf6511b94281f34617a13"
},
{
"_id": "589cf6511b94281f34617a13",
"title": "Dr.",
"firstname": "Doe",
"lastname": "John"
}
]
]
As you see, now I have a heap of arrays nested in each other. Is there a way to either unify the two sets within the array or give them proper index names?
Possible solution #1 would be this. The inner array is gone and the sets are united.
"stages": [
{
"id": "58a6678bc27c331884b60930",
"description": "Lorem ipsum dolor sit amet...",
"somevalue": 0,
"user": "589cf6511b94281f34617a13"
"_id": "589cf6511b94281f34617a13",
"title": "Dr.",
"firstname": "Doe",
"lastname": "John"
}
]
Possible solution #2: the array not gone, but at least the elements now have index names and I don't have to refer to them as [0] and [1].
"stages": [
[
"stage": {
"id": "58a6678bc27c331884b60930",
"description": "Lorem ipsum dolor sit amet...",
"somevalue": 0,
"user": "589cf6511b94281f34617a13"
},
"user": {
"_id": "589cf6511b94281f34617a13",
"title": "Dr.",
"firstname": "Doe",
"lastname": "John"
}
]
]
A virtual cookie to anyone with a solution...
Aggregation Code
db.collection('bugs').aggregate([{
$match: new ObjectId()
}, {
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'userdata'
}
},
{
$unwind: '$userdata'
},
{
$sort: {
'stages.date': -1
}
},
{
$unwind: '$stages'
}, {
$lookup: {
from: 'users',
localField: 'stages.user',
foreignField: '_id',
as: 'stages_users'
}
},
{
$unwind: '$stages_users'
}, {
$unwind: '$stages'
},
{
$group: {
'_id': '$_id',
'title': {
$first: '$title'
},
'user': {
$first: '$user'
},
'browser': {
$first: '$browser'
},
'severity': {
$first: '$severity'
},
'data': {
$first: '$data'
},
'userdata': {
$first: '$userdata'
},
'stages': {
$addToSet: {
$setUnion: [
['$stages_users'],
['$stages']
]
}
}
}
},
{
$project: {
'_id': 1,
'user': 1,
'title': 1,
'browser': 1,
'date': 1,
'severity': 1,
'userdata._id': 1,
'userdata.title': 1,
'userdata.firstname': 1,
'userdata.lastname': 1,
'stages._id': 1,
'stages.id': 1,
'stages.user': 1,
'stages.date': 1,
'stages.description': 1,
'stages.severity': 1,
'stages.previous_severity': 1,
'stages.files': 1,
'stages.title': 1,
'stages.firstname': 1,
'stages.lastname': 1
}
}
],