title: MongoDB Query: Exclude objects from child array?
body: <p>I'm working on a simple login system for my NodeJS application. For this I have created a structure where one object, a "corporation", holds an array of users. I've done because I plan to use the corporation object to store application session data.</p>
  
  <pre><code>{
      "name": "My Corporation",
      "prefix": "MYCORP",
      "users": [
          {
              "username": "some@user.com",
              "password": "974dae09cd5869958c19e1742117c2f8",
              "name": "Freddly the User"
          },
          {
              "username": "other@user.com",
              "password": "974dae09cd5869958c19e1742117c2f8",
              "name": "Max the Admin"
          }
      ]
  }
  </code></pre>
  
  <p>The problem is when querying after a user (in a log-in scenario) the query, as expected, returns the entire corporation object. Thus I'm exposing all users even though I only want one. As far as security is concerned I guess it isn't a big deal, but I'm more worried about performance. Below is the current query and a very ugly way to delete all users but the one requested.</p>
  
  <p><em>Ignore the different asserts. Code is very much work-in-progress .. :)</em></p>
  
  <pre><code>db.collection('kat_corp', function (err, collection) {
      try {
          assert.equal(null, err);
  
          collection.findOne({
              users: {
                  $elemMatch: {
                      username: user.username
                  }
              }
          }, function (err, result) {
              if (err) callback(err, false);
  
              // Delete all other users from the to-be session object
              for (var i = 0; i &lt; result.users.length; i++) {
                  if (result.users[i].username != user.username) {
                      delete result.users[i];
                  }
              }
              // Will be replaced with success callback
              console.log(result);
          });
  
      } catch (err) {
          callback(err, false);
      }
  });
  </code></pre>