Introduction
This tutorial covers the support for LINQ queries added in the 1.4 release of the C# driver.
You should already have read at least the CSharp Driver Tutorial introduction to the C# driver.
Quickstart
First, add the following additional using statement to your program:
Then, get a reference to a collection variable in the usual way:
The basic idea behind writing a LINQ query is to start from a collection variable and begin the LINQ query by calling the AsQueryable<TDocument>() method. After that it’s all standard LINQ.
For example:
You can also write queries using lambda syntax. The previous query would be written using lambda syntax like this:
The C# compiler translates all queries written using query syntax into lambda syntax internally anyway, so there is no performance advantage or penalty to choosing either style. You can also mix and match the styles, which can be useful when using query operators that are not supported by the query syntax.
All the code samples in this tutorial show both the query syntax and the lambda syntax for each query operator and supported where clauses.
Only LINQ queries that can be translated to an equivalent MongoDB query are supported. If you write a LINQ query that can’t be translated you will get a runtime exception and the error message will indicate which part of the query wasn’t supported.
注解
The 1.4 version of the C# driver requires that all where clauses that compare a field or property against a value have the constant on the right hand side. This restriction will be lifted in the next release.
Supported LINQ query operators
This section documents the supported LINQ query operators.
Any
Without a predicate Any just tests whether the collection has any documents.
Any (with predicate)
With a predicate Any tests whether the collection has any matching documents.
Note that the predicate can be provided either by a where clause or as an argument to Any, so the following are equivalent to the previous query.
Any with a predicate is not supported after a projection (at least not yet). So the following is not valid:
You can usually rewrite such a query by putting an equivalent where clause before the projection (in which case you can drop the projection).
Count
Without a predicate Count just returns the number of documents in the collection.
Count (with predicate)
With a predicate Count returns the number of documents that match the predicate.
Note that the predicate can be provided either by a where clause or as an argument to Count, so the following are equivalent to the previous query.
Count with a predicate is not supported after a projection (at least not yet). So the following is not valid:
You can usually rewrite such a query by putting an equivalent where clause before the projection (in which case you can drop the projection).
Distinct
Distinct returns the unique values of a field or property of the documents in the collection. You use a projection to identify the field or property whose distinct values you want.
The projection must select a particular field or property of the document. If the value of that field or property is represented in MongoDB as an array you can also use array indexing to select an item from the array.
ElementAt
ElementAt returns a particular document from a result set. Often you will combine this with a sort order.
If the result set has fewer documents than index ElementAt throws an exception.
ElementAtOrDefault
ElementAtOrDefault is just like ElementAt except that if there are fewer documents than index it returns null instead of throwing an exception.
First
First returns the first document from a result set. Often you will combine this with a sort order.
If the result set has no documents First throws an exception.
First (with predicate)
This overload of First allows you to provide a predicate as an argument to First. This is an alternative to using a where clause.
First with a predicate is not supported after a projection (at least not yet). So the following is not valid:
You can usually rewrite such a query by putting an equivalent where clause before the projection.
If the result set has no documents First with a predicate throws an exception.
FirstOrDefault
FirstOrDefault is just like First except that if there are no matching documents it returns null instead of throwing an exception.
FirstOrDefault (with predicate)
FirstOrDefault with a predicate is just like First with a predicate except that if there are no matching documents it returns null instead of throwing an exception.
Last
Last returns the last document from a result set. Often you will combine this with a sort order.
If the result set has no documents Last throws an exception.
Last (with predicate)
This overload of Last allows you to provide a predicate as an argument to Last. This is an alternative to using a where clause.
Last with a predicate is not supported after a projection (at least not yet). So the following is not valid:
You can usually rewrite such a query by putting an equivalent where clause before the projection.
If the result set has no documents Last throws an exception.
LastOrDefault
LastOrDefault is just like Last except that if there are no matching documents it returns null instead of throwing an exception.
LastOrDefault (with predicate)
LastOrDefault with a predicate is just like Last with a predicate except that if there are no matching documents it returns null instead of throwing an exception.
LongCount
LongCount is just like Count except that the return value is a 64-bit integer instead of a 32-bit integer.
LongCount (with predicate)
LongCount with a predicate is just like Count with a predicate except that the return value is a 64-bit integer instead of a 32-bit integer.
Max
Max returns the maximum value of a field or property of the documents in the collection. You use a projection to identify the field or property whose maximum value you want.
The projection must select a particular field or property of the document. If the value of that field or property is represented in MongoDB as an array you can also use array indexing to select an item from the array.
Max (with selector)
This overload of Max lets you select the field or property whose maximum value you want as an argument to Max instead of to Select.
Min
Min returns the minimum value of a field or property of the documents in the collection. You use a projection to identify the field or property whose minimum value you want.
The projection must select a particular field or property of the document. If the value of that field or property is represented in MongoDB as an array you can also use array indexing to select an item from the array.
Min (with selector)
This overload of Min lets you select the field or property whose minimum value you want as an argument to Min instead of to Select.
OrderBy
OrderBy is used to specify an ascending sort order for the result set.
OrderByDescending
OrderByDescending is used to specify a descending sort order for the result set.
Select
Select is used to project a new result type from the matching documents. In the 1.4 version of the C# driver a projection must typically be the last operation (with a few exceptions like Distinct, Max and Min).
Single
Single returns the first and only document from a result set.
If the result set has no documents or multiple documents Single throws an exception.
Single (with predicate)
This overload of Single allows you to provide a predicate as an argument to Single . This is an alternative to using a where clause.
Single with a predicate is not supported after a projection (at least not yet). So the following is not valid:
You can usually rewrite such a query by putting an equivalent where clause before the projection.
If the result set has no documents or multiple documents Single throws an exception.
SingleOrDefault
SingleOrDefault is just like Single except that if there are no matching documents it returns null instead of throwing an exception.
SingleOrDefault (with predicate)
SingleOrDefault with a predicate is just like Single with a predicate except that if there are no matching documents it returns null instead of throwing an exception.
Skip
Use Skip to specify how many documents to skip from the beginning of the result set. Often you will combine Skip with a sort order.
Take
Use Take to specify how many documents to return from the server. When combining Take with Skip often you will also specify a sort order.
ThenBy
ThenBy is used to specify an additional ascending sort order for the result set.
ThenByDescending
ThenByDescending is used to specify an additional descending sort order for the result set.
Where
A where clause is used to specify which documents the query should return. A where clause is a C# expression that maps the query document type to a boolean value. If the expression returns true the document “matches” the query and is included in the result set.
Sometimes a predicate can be supplied in other places besides a where clause, and it is also possible to have multiple where clauses. When multiple predicates are involved they are combined into a single composite predicate by combining the individual predicates with the && operator.
For example, the following queries are equivalent:
Supported where clauses
This section documents the supported where clauses.
As mentioned earlier, not all C# expressions are supported as a where clause. You can use this documentation as a guide to what is supported, or you can just try an expression and see if it works (a runtime exception is thrown if the where clause is not supported).
Where clauses are typically introduced using the Where query operator, but the same expressions are supported wherever a predicate is called for. In some cases multiple where clauses and predicates will be combined, in which case they are combined with the && operator.
注解
The 1.4 version of the C# driver requires that all where clauses that compare a field or property against a value have the constant on the right hand side. This restriction will be lifted in the next release.
&& (And operator)
Sub-expressions can be combined with the && operator to test whether all of them are true.
This is translated to the following MongoDB query:
In some cases the And query can’t be flattened as shown, and the $and operator will be used. The following example matches documents where X is both a multiple of 2 and a multiple of 3:
This is translated to the following MongoDB query using $and:
Any
This method is used to test whether an array field or property contains any items.
matches any document where A has 1 or more items.
This is translated to the following MongoDB query:
Boolean constant
This form is mostly for completeness. You will probably use it rarely. It allows a boolean constant to be used to either match or not match the document.
This is translated to the following MongoDB query:
Which matches all documents since the _id is a mandatory field.
Boolean field or property
A boolean field or property of the document doesn’t have to be compared to true, it can just be mentioned in the where clause and there is an implied comparison to true.
This is translated to the following MongoDB query:
Contains (Enumerable method)
This method is used to test whether an array (or array-like) field or property contains a particular value:
This is translated to the following MongoDB query:
This translation relies on the way array fields are treated by the MongoDB query language.
Contains (string method)
This method is used to test whether a string field or property of the document contains a particular substring.
This is translated to the following MongoDB query (using regular expressions):
ContainsAll (LINQ to MongoDB extension method)
This method is used to test whether an array (or array-like) field or property contains all of the provided values.
This is translated to the following MongoDB query:
ContainsAny (LINQ to MongoDB extension method)
This method is used to test whether an array (or array-like) field or property contains any of the provided values.
This is translated to the following MongoDB query:
Count method (array length)
This method is used to test whether an enumerable field or property has a certain count of items.
This is translated to the following MongoDB query:
Count property (array length)
This property is used to test whether a list (or list-like) field or property has a certain count of items.
This is translated to the following MongoDB query:
EndsWith (string method)
This method is used to test whether a string field or property of the document ends with a particular substring.
This is translated to the following MongoDB query (using regular expressions):
enum comparisons (==, !=, <, <=, >, >=)
enum fields or properties can be compared to constants of the same enum type. The relative comparison are based on the value of the underlying integer type.
This is translated to the following MongoDB query:
The LINQ implementation takes the representation of serialized values into account, so if you have configured your class map to store enums as string values instead of integer values the MongoDB query would instead be:
In (LINQ to MongoDB extension method)
The In method is used to test whether a field or property is equal any of a set of provided values.
This is translated to the following MongoDB query:
Inject
Inject is a pseudo-method that is used to inject a lower level MongoDB query into a LINQ query. The following query looks for X values that are larger than 0 and are 64-bit integers.
This is translated to the following MongoDB query:
IsMatch (regular expression method)
This method is used to test whether a string field or property matches a regular expression.
This is translated to the following MongoDB query:
You can also use the static IsMatch method.
This is translated to the following MongoDB query:
Length (array length)
This method is used to test whether an array (or array-like) field or property has a certain count of items.
This is translated to the following MongoDB query:
% (Mod operator)
This operator is used to test the result of the mod operator against a field or property of the document. The following query matches all the documents where X is odd.
This is translated to the following MongoDB query:
! (Not operator)
The ! operator is used to reverse the sense of a test.
This is translated into the following MongoDB query:
注解
!(c.X > 1) is not equivalent to (c.X <= 1) in cases where c.X is missing or does not have a numeric type.
Numeric comparisons (==, !=, <, <=, >, >=)
Numeric fields or properties can be compared using any of the above operators.
This is translated into the following MongoDB query:
|| (Or operator)
Sub-expressions can be combined with the || operator to test whether any of them is true.
This is translated to the following MongoDB query:
StartsWith (string method)
This method is used to test whether a string field or property of the document starts with a particular substring.
This is translated to the following MongoDB query (using regular expressions):
No comments:
Post a Comment