У меня проблема с group
, когда существует массив, который может быть empty
.
Коллекция может быть такой:
{
"_id" : "Contract_1",
"ContactId" : "Contact_1",
"Specifications" : [ ]
}
{
"_id" : "Contract_2",
"ContactId" : "Contact_2",
"Specifications" : [
{
"Description" : "Descrizione1",
"VehicleId" : "Vehicle_1",
"Customizations" : [
{
"Description" : "Random furniture",
"ContactId" : "Contact_5"
},
{
"Description" : "Random furniture 2",
"ContactId" : "Contact_3"
}
]
},
{
"Description" : "Descrizione2",
"VehicleId" : "Vehicle_2",
"Customizations" : [
{
"Description" : "Random furniture",
"ContactId" : "Contact_5"
},
{
"Description" : "Random furniture 2",
"ContactId" : "Contact_3"
}
]
}
]
}
{
"_id" : "Contract_3",
"ContactId" : "Contact_25",
"Specifications" : [
{
"Description" : "Descrizione1",
"VehicleId" : "Vehicle_1",
"Customizations" : []
},
{
"Description" : "Descrizione2",
"VehicleId" : "Vehicle_2",
"Customizations" : []
}
]
}
Как видите, иногда Specifications
может быть нулевым, а также Customizations
.
И это запрос, который я выполняю:
db.getCollection("Contract").aggregate([
{ "$lookup": {
"from": "Contact",
"localField": "ContactId",
"foreignField": "_id",
"as": "Contact"
}},
{ "$unwind": {"path":"$Contact", "preserveNullAndEmptyArrays":true }},
{ "$unwind": { "path": "$Specifications", "preserveNullAndEmptyArrays":true }},
{ "$lookup": {
"from": "Vehicle",
"localField": "Specifications.VehicleId",
"foreignField": "_id",
"as": "Specifications.Vehicle"
}},
{ "$unwind": {"path": {"$Specifications.Vehicle","preserveNullAndEmptyArrays":true} },
{ "$unwind": {"path": {"$Specifications.Customizations","preserveNullAndEmptyArrays":true} },
{ "$lookup": {
"from": "Contact",
"localField": "Specifications.Customizations.ContactId",
"foreignField": "_id",
"as": "Specifications.Customizations.Contact"
}},
{ "$unwind": {"path": {"$Specifications.Customizations.Contact","preserveNullAndEmptyArrays":true} },
{ "$group": {
"_id": {
"_id": "$_id",
"Description": "$Specifications.Description"
},
"ContactId": { "$first": "$ContactId" },
"Contact": { "$first": "$Contact" },
"Specifications": {
"$push": "$Specifications.Customizations"
}
}},
{ "$group": {
"_id": "$_id._id",
"ContactId": { "$first": "$ContactId" },
"Contact": { "$first": "$Contact" },
"Specifications": {
"$push": {
"Description": "$_id.Description",
"Customizations": "$Specifications"
}
}
}}
])
}},
{ "$group": {
"_id": "$_id._id",
"ContactId": { "$first": "$ContactId" },
"Contact": { "$first": "$Contact" },
"Specifications": {
"$push": {
"Description": "$_id.Description",
"Customizations": "$Specifications"
}
}
}}
])
Как только запрос выполняется, когда он выполняет 2 $group
, это создает проблему, поскольку для первого, когда pushing
$Specifications.Customizations
создаст массив с пустым элементом внутри. То, что я хочу, это то, что если Specifications
является пустым массивом, останется без добавления пустого элемента внутрь.