Find Documents with missing properties in Azure DocumentDb with the .Net SDK
by Frans Lytzen | 07/02/2017
Azure DocumentDb stores documents as JSON. One of the effects of this is that sometimes you may end up with documents in the database that have missing properties and it can be quite tricky to search for them with the .Net SDK. This blog post has an approach to doing it - and quite simply too.
Background
JsonConvert.DefaultSettings = () =>
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
For example, imagine you have a class called MyItem looking like this:
public class MyItem
{
[JsonProperty("id")]
public string Id { get; set; }
public string SomeValue { get; set; }
}
{
"id" : "1",
"SomeValue" : null
}
{
"id" : "1",
}
Selecting missing properties with SQL
SELECT f.lastName ?? f.surname AS familyName
FROM Families f
Finding items with null or missing with the .Net SDK
var query1 = client.CreateDocumentQuery<MyItem>(collectionUrl)
.Where(i => i.SomeValue == null);
var query2 = client.CreateDocumentQuery<MyItem>(collectionUrl)
.Where(i => (i.SomeValue ?? null) == null);
I have tested this with version 1.6, 1.8 and 1.10 of the SDK, but I would advise you to put an integration test in your code if you are going to rely on it, just in case the behaviour changes in the future. You'll probably also want to put a comment wherever you use this syntax as R# is quite keen to tell you that you should get rid of the "?? null" part.
Finally, I have not done any performance testing on this, but I suspect DocumentDb won't be able to use any indexes to execute this query; it will probably have to evaluate each document in a scan so use with caution.