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

Asked

Viewed 28 times

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?

1 answer

2


People got it, just project 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'}
}
])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.