dotConnect for MongoDB supports parameters both in SQL statements and in native MongoDB commands. This article describes the basics of working with parameters in dotConnect for MongoDB and automatic parameter synchronization.
In general, a parameter is a placeholder for a variable that contains a value of a certain type when a general-purpose query is executed. A parameter is represented by the MongoDBParameter class. All parameters that take part in query execution constitute a collection that can be accessed through the MongoDBCommand.Parameters property.
Parameters in the query text must correspond to the names of the MongoDBParameter instances in the collection. Named parameters are declared using the ':' or '@' prefix followed by the parameter name. Use the name of the MongoDBParameter object in the command's collection without any prefix. You can use these prefixes in any combination. Named parameters have two main advantages. First, you don't have to care about the order in which parameters are created. Second, a named parameter can appear more than once in the query text, but you have to create only one instance of it in the Parameters collection.
You can also use the '?' positional parameter marker. In this case, parameters are bound in the order in which they're added to the collection. Note that '$name' isn't a parameter marker because MongoDB operators start with '$'.
dotConnect for MongoDB supports only input parameters (ParameterDirection.Input) because MongoDB has no stored procedures.
For example, a simple UPDATE statement with named parameters might look like the following:
To set parameters for this query, you can use the following code:
In native mode (the Sql Engine connection string parameter is set to False), the command text is a MongoDB database command in Extended JSON. Parameters are substituted into the JSON text on the client side, and string values are escaped. A parameter of the MongoDBType.Object type is inserted as a JSON document. For example, the following command gets the filter from the filter parameter:
The behavior described above assumes that MongoDBCommand.ParameterCheck is false (default). If you set it to true, you enable automatic synchronization of the query text and the MongoDBCommand.Parameters collection. In this mode, all input parameters are checked for validity, new ones are added if necessary, and redundant parameters are deleted. Thus, you don't have to care about the number of items in the MongoDBCommand.Parameters collection and can specify only the ones you really need. The synchronization is performed as follows:
The synchronization takes place when: