I'm starting in MongoDB and would like to do a query on my bank like: 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'}
}
])
Saida:
{ "_id" : "014" }
{ "_id" : "001" }
But if I change '$ _id' to '$ 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'}
}
])
Return is { "_id" : null }
.
The only way I found to return 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'}
}
])
Output:
{ "_id" : "Golias" }
{ "_id" : "Zoe" }
Does anyone know how to return the 'nickname' field using $ project?