单投影 child object

Projection with single child object

假设我有类似的东西:

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

我想做一个 find(),在我的投影中我只想要 student2,这是 child object/attribute 的 grades

我的幼稚做法:

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

没有用,所以我调查了 http://docs.mongodb.org/manual/reference/operator/projection/,我想也许 $slice 会是我想要的,但似乎不是。

你可以access fields inside an embedded document using the dot notation。不要忘记引用字段名称。

> 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 } }

请注意 _id 是隐式投影的。你不必指定它,除非你想删除它 (_id: 0)。