In MongoDB query, how to get a field in _id included nested document

178 views Asked by At

Assume one document in student collection as follows:

{
  _id:{
       time: 1
       loc: 'A'
      },
 name: 'Jery'
}

I want to filter _id.time, like so:

db.student.find({}, {'_id.time':1})

But I got a result:

{
 _id:{
      time: 1
      loc: 'A'
     }
}

Why the result is not as follows:

{
 _id:{
      time: 1
     }
}

So, where is my error? And how to write the query operation.

Thank you.

1

There are 1 answers

2
Kevin Smith On BEST ANSWER

Just tried a few things but it seems to be a limitation:

> db.students.find({}, {'_id':0, '_id.time': 1})
{  }
{  }

> db.students.find({}, {'_id.loc':0, '_id.time': 1})
Error: error: {
        "ok" : 0,
        "errmsg" : "Projection cannot have a mix of inclusion and exclusion.",
        "code" : 2,
        "codeName" : "BadValue"
}

You can however easily achieve this with an aggregation query with a $project stage.

> db.students.aggregate( { $project: { '_id.time':1 } } )
{ "_id" : { "time" : 1 } }
{ "_id" : { "time" : 2 } }