Projection with single child object

45 views Asked by At

Say I have something like:

{ "_id" : 1, "semester" : 1, "grades" : { student1: 70, student2: 85 }}
{ "_id" : 1, "semester" : 1, "grades" : { student1: 55, student2: 24 }}

I want to do a find() and in my projection I just want student2, which is a child object/attribute of grades

My naive approach:

db.streets.find({dowhatever}, {_id:1, grades.student2: 1})

Didn't work so then I looked into http://docs.mongodb.org/manual/reference/operator/projection/ and I thought maybe $slice would be what I want, but doesn't seem to be.

1

There are 1 answers

1
Sylvain Leroux On BEST ANSWER

You can access fields inside an embedded document using the dot notation. Don't forget to quote the field name though.

> db.collection.find()
{ "_id" : 1, "semester" : 1, "grades" : { "student1" : 70, "student2" : 85 } }
{ "_id" : 2, "semester" : 2, "grades" : { "student1" : 55, "student2" : 24 } }

> db.collection.find({_id: 2}, { "grades.student2": 1})
{ "_id" : 2, "grades" : { "student2" : 24 } }

Please note that _id is implicitly projected. You don't have to specify it, unless you want to remove it (_id: 0).