I use the following query:
Collection
.aggregate([
{
$project : { follow_count: {$size: { "$ifNull": [ "$follow_users", [] ] } } }
},
{ $lookup: {from: 'models', localField: '_id', foreignField: '_id', as: 'model'}},
])
to get this kind of JSON:
[
{
"_id": "1234565434567",
"follow_count": 3,
"model": [
{
"_id": "1234565434567",
"make": "Make1",
"name": "Model1",
"price": 15200,
}
]
},
{
"_id": "123456789",
"follow_count": 2,
"model": [
{
"_id": "123456789",
"make": "Make2",
"name": "Model2",
"price": 12000,
}
]
}
]
Is there a way to don't push the $lookup result inside an array to have a JSON like that? I prefer to don't use loops after the query, so I am looking for an optimized way.
[
{
"_id": "1234565434567",
"follow_count": 3,
"make": "Make1",
"name": "Model1",
"price": 15200,
},
{
"_id": "123456789",
"follow_count": 2,
"make": "Make2",
"name": "Model2",
"price": 12000,
}
]