The most important practice is to as much as possible stick to APIs that don't involve string concatenation. Many of the database drivers seem to include fluent APIs where query language is reflected in the programming language. The .NET implementation called mongodb-net, has a syntax like this: coll.FindOne(Where.Field(a => a == 1));
This allows you to develop without thinking about how the query is actually constructed. The escaping is (hopefully) performed by the framework.
Mathias Stearn also mentioned this API for building safe queries:queryObj.append("b", 2)
When using the insecure APIs like:db.myCollection.find("{ $where: 'this.a > " + userinput + "' }");
ordb.foo.find("{ $or : [ { a : 1 } , { b : " + userinput + " } ] }")
make sure you pay close attention. Whenever you do string concatenation, you need to escape the data correctly. MongoDB supports converting javascript queries to it's native query language expressed in BSON. When using this, there are two contexts you need to be aware of:
If you are concatenating user input outside a string, you really need to be careful. It's really hard to get the escaping right unless the datatype of the variable is an integer or similar where the possible values are known and limited.
Update 2010-08-02: If you are using MongoDB from PHP, you might want to look at blog post from Phil