[modifica basata sul fatto che ora questo è possibile nelle versioni recenti]
[Risposta aggiornata] Puoi interrogare nel modo seguente per ottenere indietro il nome della classe e l'id dello studente solo se sono già iscritti.
db.student.find({}, {_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}}) e otterrai indietro ciò che ti aspettavi:
{ "name" : "CS 101", "students" : [ ObjectId("51780f796ec4051a536015cf") ] } { "name" : "Literature" } { "name" : "Physics", "students" : [ ObjectId("51780f796ec4051a536015cf") ] } [Risposta originale] Al momento non è possibile fare ciò che vuoi. È un peccato perché potresti farlo se lo studente fosse memorizzato nell'array come oggetto. In effetti, sono un po' sorpreso che tu stia usando solo ObjectId() perché ciò ti costringerà sempre a cercare gli studenti se vuoi visualizzare un elenco di studenti iscritti a un particolare corso (cerca prima l'elenco degli Id e poi cerca i nomi nella collezione students: due query invece di una!)
Se memorizzassi (ad esempio) un Id e un nome nell'array course così:
{ "_id" : ObjectId("51780fb5c9c41825e3e21fc6"), "name" : "Physics", "students" : [ {id: ObjectId("51780f796ec4051a536015cf"), name: "John"}, {id: ObjectId("51780f796ec4051a536015d0"), name: "Sam"} ] } La tua query allora sarebbe semplicemente:
db.course.find( { }, { students : { $elemMatch : { id : ObjectId("51780f796ec4051a536015d0"), name : "Sam" } } } ); Se quello studente fosse iscritto solo a CS 101 otterresti indietro:
{ "name" : "Literature" } { "name" : "Physics" } { "name" : "CS 101", "students" : [ { "id" : ObjectId("51780f796ec4051a536015cf"), "name" : "John" } ] }