5
I’m starting in Mongodb and would like to perform a consultation in my database of type: Which animals got sick in the year 2016?
Using $group and $project:
db.animais.aggregate([
{$unwind : "$doencas" },
{$project : {
year : {$year : "$doencas.data_diagnostico"}
}},
{$match : {year :{$eq: 2016}}},
{$group:{
_id:'$_id'}
}
])
Satida:
{ "_id" : "014" }
{ "_id" : "001" }
But if I change '$_id' for '$nickname':
db.animais.aggregate([
{$unwind : "$doencas" },
{$match : {"doencas.data_diagnostico":{$gt: new Date(2015,11,31)}}},
{$match : {"doencas.data_diagnostico":{$lt: new Date(2017,01,01)}}},
{$group:{
_id:'$apelido'}
}
])
The return is { "_id" : null }
.
The only way I could do it by returning the nickname is not to use $project, for example:
db.animais.aggregate([
{$unwind : "$doencas" },
{$match : {"doencas.data_diagnostico":{$gt: new Date(2015,11,31)}}},
{$match : {"doencas.data_diagnostico":{$lt: new Date(2017,01,01)}}},
{$group:{
_id:'$apelido'}
}
])
Exit:
{ "_id" : "Golias" }
{ "_id" : "Zoe" }
Does anyone know how to return the 'nickname' field by making use of $project?