title: Predicting index key length for a string in MongoDb
body: <p>I have a document of the form</p>
  
  <pre><code>{
      itemId: SomeInteger
      .... A bunch of other stuff
      IndexedArrayOfStrings: [string1, string2, etc]
  }
  </code></pre>
  
  <p>IndexedArrayOfStrings has an index on it.  I have some strings that are so long that they break the max size of 1024 bytes of an item in an index.  Normally, I would test this by converting the item to BSON, and test the length of the string.  However, when I try to convert the string to BSON, I get the following error:</p>
  
  <pre><code>byte[] payload = doc.IndexedArrayOfStrings[0].ToBson();
  
  System.InvalidOperationException : A String value cannot be written to the root level of a BSON document.
  </code></pre>
  
  <p>My best attempt to get an estimate of the size is use the following code to get the bson:</p>
  
  <pre><code>byte[] payload = new {IndexedArrayOfStrings = doc.IndexedArrayOfStrings}.ToBson();
  </code></pre>
  
  <p>This gives me more than a single string will.  A string of a repeated "a" with length 1012 has a bson of length 1051, and the length of payload will vary, depending on the name of the property.  The max length of the string at the point the indexing fails is the same, regardless of the name of the property.  In this simple string, the largest string that can be indexed is 1012, but the binary length of a UTF-16 string is not precisely proportional to it's human legible length.</p>
  
  <p>Is there a better way to predict the length of the indexed value before sending it to Mongo?</p>