title: MongoDB Conditional validation on arrays and embedded documents
body: <p>I have a number of documents in my database where I am applying document validation. All of these documents may have embedded documents. I can apply simple validation along the lines of SQL non NULL checks (these are essentially enforcing the primary key constraints) but what I would like to do is apply some sort of conditional validation to the optional arrays and embedded documents. By example, lets say I have a document that looks like this:</p>
  
  <pre><code>{
    "date": &lt;&lt;insertion date&gt;&gt;,
    "name" : &lt;&lt;the portfolio name&gt;&gt;,
    "assets" : &lt;&lt; amount of money we have to trade with&gt;&gt;
  }
  </code></pre>
  
  <p>Clearly I can put validation on this document to ensure that date name and assets all exist at insertion time. Lets say, however, that I'm managing a stock portfolio and the document can have future updates to show an array of stocks like this:</p>
  
  <pre><code>{
    "date"      : &lt;&lt;insertion date&gt;&gt;,
    "name"      : &lt;&lt;the portfolio name&gt;&gt;,
    "assets"    : &lt;&lt; amount of money we have to trade with&gt;&gt;
    "portfolio" : [
                    { "stockName"  : "IBM",
                      "pricePaid"  : 155.39,
                      "sharesHeld" : 100
                    },
                    { "stockName"  : "Microsoft",
                      "pricePaid"  : 57.22,
                      "sharesHeld" : 250
                    }
                  ]
  }
  </code></pre>
  
  <p>Is it possible to to apply a conditional validation to this array of sub documents? It's valid for the portfolio to not be there but if it is each document in the array must contain the three fields "stockName", "pricePaid" and "sharesHeld".</p>