(+N) Consulting Inc.

Consulting. Software solutions. Training.

Query Oddities – MongoDB style

Oh, I remember it like it was yesterday: Dot-com, no DBA, late nights, a pale developer walking into my office head hung low and mumbling something about restoring backup because he ran an update query with no where clause.. the good old days. Zoom forward a decade. A developer is cranking away on some MongoDB query generation in code. Not wanting to make any rookie mistakes, she uses the Query.EQ builder, which would surely create the correct syntax. Better than her own string.Format() at least! Or so she thought. The issue is a small peculiarity with the Query methods. The formal signature takes a string and a BsonValue: 1: public static QueryComplete EQ( 2: string name, 3: BsonValue value 4: ) So a some call path would get to a method which would create the query. Lets say 1: public string CreateFooQuery(string value) 2: { 3: var query = Query.EQ("Prop1",value); 4: return query.ToString(); 5: }   Did you spot the issue? I didn't. She didn't either. The issue is that the Query.EQ method would boil down a value "xyz" to the MongoDB query {"Prop1":"xyz"} just fine. It would also boil down an empty string "" to the query {"Prop1":""} without flinching. But if you supply null – and yes, strings can be null – then the query becomes {}. Yes, that's right, the null query. Yes, the one that matches EVERY document! Now take that query as a read query – you got all documents returned. Use it for an update – might as well have some good backup strategy! Note to self: write more unit tests. Ensure that every code path you visit have been visited before and the expected values are returned. Sigh!