title: MongoDB: How to find out if an array field contains an element?
body: <p>I have two collections.  The first collection contains students:</p>
  
  <pre><code>{ "_id" : ObjectId("51780f796ec4051a536015cf"), "name" : "John" }
  { "_id" : ObjectId("51780f796ec4051a536015d0"), "name" : "Sam" }
  { "_id" : ObjectId("51780f796ec4051a536015d1"), "name" : "Chris" }
  { "_id" : ObjectId("51780f796ec4051a536015d2"), "name" : "Joe" }
  </code></pre>
  
  <p>The second collection contains courses:</p>
  
  <pre><code>{
          "_id" : ObjectId("51780fb5c9c41825e3e21fc4"),
          "name" : "CS 101",
          "students" : [
                  ObjectId("51780f796ec4051a536015cf"),
                  ObjectId("51780f796ec4051a536015d0"),
                  ObjectId("51780f796ec4051a536015d2")
          ]
  }
  {
          "_id" : ObjectId("51780fb5c9c41825e3e21fc5"),
          "name" : "Literature",
          "students" : [
                  ObjectId("51780f796ec4051a536015d0"),
                  ObjectId("51780f796ec4051a536015d0"),
                  ObjectId("51780f796ec4051a536015d2")
          ]
  }
  {
          "_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
          "name" : "Physics",
          "students" : [
                  ObjectId("51780f796ec4051a536015cf"),
                  ObjectId("51780f796ec4051a536015d0")
          ]
  }
  </code></pre>
  
  <p>Each course document contains <code>students</code> array which has a list of students registered for the course.  When a student views a course on a web page he needs to see if he has already registered for the course or not.  In order to do that, when the <code>courses</code> collection gets queried on the student's behalf, we need to find out if <code>students</code> array already contains the student's ObjectId.  Is there a way to specify in the projection of a find query to retrieve student <code>ObjectId</code> from <code>students</code> array only if it is there?</p>
  
  <p>I tried to see if I could $elemMatch operator but it is geared towards an array of sub-documents.  I understand that I could use aggregation framework but it seems that it would be on overkill in this case.  Aggregation framework would probably not be as fast as a single find query.  Is there a way to query course collection to so that the returned document could be in a form similar to this?</p>
  
  <pre><code>{
          "_id" : ObjectId("51780fb5c9c41825e3e21fc4"),
          "name" : "CS 101",
          "students" : [
                  ObjectId("51780f796ec4051a536015d0"),
          ]
  }
  </code></pre>