Hi @Matteo_Tarantino ,
I believe you can achieve that with games on $count and $redact for specific parents, using a $merge eventually.
For example the following aggregation:
[{$match: {
parent: 'myparent'
}}, {$group: {
_id: '$parent',
count: {
$count: {}
}
}}, {$redact: {
$cond: {
'if': {
$gte: [
'$count',
3
]
},
then: '$$PRUNE',
'else': '$$KEEP'
}
}}, {$addFields: {
createDocument: {
_id: ObjectId('6208e7c09c02b5bbe1391e8e'),
parent: 'myparent',
value: 5
}
}}, {$replaceRoot: {
newRoot: '$createDocument'
}}, {$merge: {
into: 'myparents',
on: '_id',
whenMatched: 'fail',
whenNotMatched: 'insert'
}}]
If the grouping and counting for a specific parent yeild a result of less or equal than 3 the document will be kept and we can use “$addFields” to add the new document we wish to insert under “createDocument” field.
Now this is a pretty complex agg for something stratigicaly small. Have you considered changing the document model to have children of a parent under the same parent?
Thanks,
Pavel