I can not return another field other than the primary key using $ project

5

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?

    
asked by anonymous 10.12.2016 / 17:09

1 answer

2

People got it, it was just designing the attribute I wanted to show.

db.animais.aggregate([
{$unwind : "$doencas" },
{$project : {
    year : {$year : "$doencas.data_diagnostico"},
    apelido: 1
}},
{$match : {year :{$eq: 2016}}},
{$group:{
   _id:'$apelido'}
}
])
    
10.12.2016 / 17:28