mongodb driver c#语法
Definitions and Builders
The driver has introduced a number of types related to the specification of filters, updates, projections, sorts, and index keys. These types are used throughout the API.
Most of the definitions also have builders to aid in their creation. Each builder has a generic type parameter TDocument which represents the type of document with which you are working. It will almost always match the generic TDocument parameter used in an IMongoCollection<TDocument>.
Fields
FieldDefinition<TDocument> and FieldDefinition<TDocument, TField> define how to get a field name. They are implicitly convertible from a string, so that you can simply pass the field name you’d like. For instance, to use the field named “fn” with a TDocument of BsonDocument, do the following:
FieldDefinition<BsonDocument> field = "fn";
However, if you are working with a mapped class, then we are able to translate a string that equals the property name. For instance, given the below Person class:
class Person
{
[BsonElement("fn")]
public string FirstName { get; set; }
[BsonElement("ln")]
public string LastName { get; set; }
}
Since we know the type is Person, we can provide the property name, FirstName, from the class and “fn” will still be used.
FieldDefinition<Person> field = "FirstName";
NOTE
We don’t validate that the provided string exists as a mapped field, so it is still possible to provide a field that hasn’t been mapped:
FieldDefinition<Person> field = "fn";
And the output field name of this will be just “fn”.
Filters
FilterDefinition<TDocument> defines a filter. It is implicity convertible from both a JSON string as well as a BsonDocument.
FilterDefinition<BsonDocument> filter = "{ x: 1 }";
// or
FilterDefinition<BsonDocument> filter = new BsonDocument("x", 1);
Both of these will render the filter { x: 1 }.
Filter Definition Builder
See the tests for examples.
The FilterDefinitionBuilder<TDocument> provides a type-safe API for building up both simple and complex MongoDB queries.
For example, to build up the filter { x: 10, y: { $lt: 20 } }, the following calls are all equivalent.
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq("x", 10) & builder.Lt("y", 20);
NOTE
The & operator is overloaded. Other overloaded operators include the | operator for “or” and the ! operator for “not”.
Given the following class:
class Widget
{
[BsonElement("x")]
public int X { get; set; }
[BsonElement("y")]
public int Y { get; set; }
}
You can achieve the same result in the typed variant:
var builder = Builders<Widget>.Filter;
var filter = builder.Eq(widget => widget.X, 10) & builder.Lt(widget => widget.Y, 20);
The benefits to this form is the compile-time safety inherent in using types. In addition, your IDE can provide refactoring support.
Alternatively, you can elect to use a string-based field name instead.
var filter = builder.Eq("X", 10) & builder.Lt("Y", 20);
// or
var filter = builder.Eq("x", 10) & builder.Lt("y", 20);
For more information on valid lambda expressions, see the expressions documentation.
Array Operators
When using entities with properties or fields that serialize to arrays, you can use the methods prefixed with “Any” to compare the entire array against a single item.
Given the following class:
public class Post
{
public IEnumerable<string> Tags { get; set; }
}
To see if any of the tags equals “mongodb”:
var filter = Builders<Post>.Filter.AnyEq(x => x.Tags, "mongodb");
// This will NOT compile:
// var filter = Builders<Post>.Filter.Eq(x => x.Tags, "mongodb");
Pipelines
A pipeline definition defines an entire aggregation pipeline. It is implicitly convertible from a List<BsonDocument>, a BsonDocument, a List<IPipelineStageDefinition> , and a IPipelineStageDefinition[].
For example:
PipelineDefinition pipeline = new BsonDocument[]
{
new BsonDocument { { "$match", new BsonDocument("x", 1) } },
new BsonDocument { { "$sort", new BsonDocument("y", 1) } }
};
NOTE
There is no builder for a PipelineDefinition. In most cases, the IAggregateFluent<TDocument> interface would be used which is returned from the IMongoCollection<TDocument>.Aggregate method.
Projections
There are two forms of a projection definition: one where the type of the projection is known, ProjectionDefinition<TDocument, TProjection>, and one where the type of the projection is not yet known, ProjectionDefinition<TDocument>. The latter, while implicitly convertible to the first, is merely used as a building block. The high-level APIs that take a projection will always take the former. This is because, when determining how to handle a projection client-side, it is not enough to know what fields and transformations will take place. It also requires that we know how to interpret the projected shape as a .NET type. Since the driver allows you to work with custom classes, it is imperative that any projection also include the “interpretation instructions” for projecting into a custom class.
Each projection definition is implicity convertible from both a JSON string as well as a BsonDocument.
ProjectionDefinition<BsonDocument> projection = "{ x: 1 }";
// or
ProjectionDefinition<BsonDocument> projection = new BsonDocument("x", 1);
Both of these will render the projection { x: 1 }.
Projection Definition Builder
See the tests for examples.
The ProjectionDefinitionBuilder<TDocument> exists to make it easier to build up projections in MongoDB’s syntax. For the projection { x: 1, y: 1, _id: 0 }:
var projection = Builders<BsonDocument>.Projection.Include("x").Include("y").Exclude("_id");
Using the Widget class:
class Widget
{
public ObjectId Id { get; set; }
[BsonElement("x")]
public int X { get; set; }
[BsonElement("y")]
public int Y { get; set; }
}
We can render the same projection in a couple of ways:
var projection = Builders<Widget>.Projection.Include("X").Include("Y").Exclude("Id");
// or
var projection = Builders<Widget>.Projection.Include("x").Include("y").Exclude("_id");
// or
var projection = Builders<Widget>.Projection.Include(x => x.X).Include(x => x.Y).Exclude(x => x.Id);
// or
var projection = Builders<Widget>.Projection.Expression(x => new { X = x.X, Y = x.Y });
This last projection where we’ve used the Expression method is subtly different as is explained below, and its return type is a (ProjectionDefinition<TDocument, TProjection>) as opposed to the others which return a (ProjectionDefinition<TDocument>).
Lambda Expressions
The driver supports using expression trees to render projections. The same expression tree will sometimes render differently when used in a Find operation versus when used in an Aggregate operation. Inherently, a lambda expression contains all the information necessary to form both the projection on the server as well as the client-side result and requires no further information.
Find
See the tests for examples.
When a Find projection is defined using a lambda expression, it is run client-side. The driver inspects the lambda expression to determine which fields are referenced and automatically constructs a server-side projection to return only those fields.
Given the following class:
class Widget
{
public ObjectId Id { get; set; }
[BsonElement("x")]
public int X { get; set; }
[BsonElement("y")]
public int Y { get; set; }
}
The following lambda expressions will all result in the projection { x: 1, y: 1, _id: 0 }. This is because we inspect the expression tree to discover all the fields that are used and tell the server to include them. We then run the lambda expression client-side. As such, Find projections support virtually the entire breadth of the C# language.
var projection = Builders<Widget>.Projection.Expression(x => new { X = x.X, Y = x.Y });
var projection = Builders<Widget>.Projection.Expression(x => new { Sum = x.X + x.Y });
var projection = Builders<Widget>.Projection.Expression(x => new { Avg = (x.X + x.Y) / 2 });
var projection = Builders<Widget>.Projection.Expression(x => (x.X + x.Y) / 2);
The _id field is excluded automatically when we know for certain that it isn’t necessary, as is the case in all the above examples.
Aggregate
See the tests for examples.
When an aggregate projection is defined using a lambda expression, a majority of the aggregation expression operators are supported and translated. Unlike a project for Find, no part of the lambda expression is run client-side. This means that all expressions in a projection for the Aggregation Framework must be expressible on the server.
Grouping
See the tests for examples.
A projection is also used when performing grouping in the Aggregation Framework. In addition to the expression operators used in an aggregate projection, the aggregation accumulator operators are also supported.
Sorts
SortDefinition<TDocument> defines how to render a valid sort document. It is implicity convertible from both a JSON string as well as a BsonDocument.
SortDefinition<BsonDocument> sort = "{ x: 1 }";
// or
SortDefinition<BsonDocument> sort = new BsonDocument("x", 1);
Both of these will render the sort { x: 1 }.
Sort Definition Builder
See the tests for examples.
The SortDefinitionBuilder<TDocument> provides a type-safe API for building up MongoDB sort syntax.
For example, to build up the sort { x: 1, y: -1 }, do the following:
var builder = Builders<BsonDocument>.Sort;
var sort = builder.Ascending("x").Descending("y");
Given the following class:
class Widget
{
[BsonElement("x")]
public int X { get; set; }
[BsonElement("y")]
public int Y { get; set; }
}
We can achieve the same result in the typed variant:
var builder = Builders<Widget>.Sort;
var sort = builder.Ascending(x => x.X).Descending(x => x.Y);
// or
var sort = builder.Ascending("X").Descending("Y");
// or
var sort = builder.Ascending("x").Descending("y");
Updates
UpdateDefinition<TDocument> defines how to render a valid update document. It is implicity convertible from both a JSON string as well as a BsonDocument.
// invocation
UpdateDefinition<BsonDocument> update = "{ $set: { x: 1 } }";
// or
UpdateDefinition<BsonDocument> update = new BsonDocument("$set", new BsonDocument("x", 1));
Both of these will render the update { $set: { x: 1 } }.
Update Definition Builder
See the tests for examples.
The UpdateDefinitionBuilder<TDocument> provides a type-safe API for building the MongoDB update specification.
For example, to build up the update { $set: { x: 1, y: 3 }, $inc: { z: 1 } }, do the following:
var builder = Builders<BsonDocument>.Update;
var update = builder.Set("x", 1).Set("y", 3).Inc("z", 1);
Given the following class:
class Widget
{
[BsonElement("x")]
public int X { get; set; }
[BsonElement("y")]
public int Y { get; set; }
[BsonElement("z")]
public int Z { get; set; }
}
We can achieve the same result in a typed variant:
var builder = Builders<Widget>.Update;
var update = builder.Set(widget => widget.X, 1).Set(widget => widget.Y, 3).Inc(widget => widget.Z, 1);
// or
var update = builder.Set("X", 1).Set("Y", 3).Inc("Z", 1);
// or
var update = builder.Set("x", 1).Set("y", 3).Inc("z", 1);
Index Keys
IndexKeysDefinition<TDocument> defines the keys for index. It is implicity convertible from both a JSON string as well as a BsonDocument.
IndexKeysDefinition<BsonDocument> keys = "{ x: 1 }";
// or
IndexKeysDefinition<BsonDocument> keys = new BsonDocument("x", 1);
Both of these will render the keys { x: 1 }.
Index Keys Definition Builder
See the tests for examples.
The IndexKeysDefinitionBuilder<TDocument> provides a type-safe API to build an index keys definition.
For example, to build up the keys { x: 1, y: -1 }, do the following:
var builder = Builders<BsonDocument>.IndexKeys;
var keys = builder.Ascending("x").Descending("y");
Given the following class:
class Widget
{
[BsonElement("x")]
public int X { get; set; }
[BsonElement("y")]
public int Y { get; set; }
}
We can achieve the same result in the typed variant:
var builder = Builders<Widget>.IndexKeys;
var keys = builder.Ascending(x => x.X).Descending(x => x.Y);
// or
var keys = builder.Ascending("X").Descending("Y");
// or
var keys = builder.Ascending("x").Descending("y");
mongodb driver c#语法的更多相关文章
- C# mongoDB Driver 使用对象方式查询语法大全
#region 查询方法 /// <summary> /// 获取单个对象 /// </summary> /// <typeparam name="T" ...
- MongoDB update数据语法【转】
在前面的文章“mongodb 查询的语法”里,我介绍了Mongodb的常用查询语法,Mongodb的update操作也有点复杂,我结合自己的使用经验,在这里介绍一下,给用mongodb的朋友看看,也方 ...
- MongoDB Driver 简单的CURD
c#中我们可以使用MongoDB.Driver驱动进行对MongoDB数据库的增删改查. 首先需要在NuGet中安装驱动 安装完毕后会发现会有三个引用 其中 MongoDB.Driver和MongoD ...
- c# MongoDB Driver 官方教程翻译
先贴官方文档地址:http://mongodb.github.io/mongo-csharp-driver/2.5/getting_started/quick_tour/ 安装部分很简单,nuget搜 ...
- 基于MongoDB.Driver的扩展
由于MongoDB.Driver中的Find方法也支持表达式写法,结合[通用查询设计思想]这篇文章中的查询思想,个人基于MongoDB扩展了一些常用的方法. 首先我们从常用的查询开始,由于MongoD ...
- MongoDB系列:五、MongoDB Driver使用正确的姿势连接复制集
MongoDB复制集(Replica Set)通过存储多份数据副本来保证数据的高可靠,通过自动的主备切换机制来保证服务的高可用.但需要注意的时,连接副本集的姿势如果不对,服务高可用将不复存在. 使用复 ...
- php MongoDB driver 查询实例
//是否只查mx $mx_on_switch = I("post.mx_on_switch"); //mx模糊查询 $mx_vague_check = I("post.m ...
- Mongodb与mysql语法比较
Mongodb与mysql语法比较 mongodb与mysql命令对比 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由 ...
- MongoDB.Driver 2.4以上版本 在.NET中的基本操作
MongoDB.Driver是操作mongo数据库的驱动,最近2.0以下版本已经从GitHub和Nuget中移除了,也就是说.NET Framework4.0不再能从官方获取到MongoDB的驱动了, ...
随机推荐
- ubuntu14.04 LTS 更新源
官方源: deb http://archive.ubuntu.com/ubuntu/ trusty main restricted universe multiverse deb http://arc ...
- FFmpeg编译出错_img_convert 找不到
问题出现在下载的ffmpeg的版本不一样,在0.4.8以前的版本中还有img_convert这个函数,新版本中用sws_getContext和sws_scale代替了.简单说明如下: 新版本的ffmp ...
- 写给已有编程经验的 Python 初学者的总结
当我开始学习Python的时候,有些事我希望我一早就知道.我花费了很多时间才学会这些东西.我想要把这些重点都编纂到一篇文章当中.这篇文章的目标读者,是刚刚开始学习Python语言的有经验的程序员,想要 ...
- Form personization(Form 个性化)报无权限
总部的同事利用form personization对工单的一些Form做了个性化,发现可能设的有问题,造成用户无法关工单.想要看一下她是怎么设的,可报没权限.经过研究发现,把个人Profile 的 U ...
- 条件注释判断浏览器<!--[if !IE]><!--[if IE]><!--[if lt IE 6]><!--[if gte IE 6]>
<!--[if !IE]><!--> 除IE外都可识别 <!--<![endif]--><!--[if IE]> 所有的IE可识别 <![e ...
- php随机密码函数的实例代码
php随机密码函数的入门例子 时间:2015-12-16 20:42:48来源:网络 导读:php生成随机密码的函数实例,php生成随机密码的函数,生成数字.大小写字母与特殊字符组合的随机密码. ...
- 从头学Qt Quick(2)-- QML语法从一个简单的例子说起
在上一篇文章中,我们对QtQuick做了简单的介绍,体验了使用QML语言构建一个UI的便捷.这里我们简要介绍一下QML的语法. QML将界面分成一些更小的元素,这些元素可以组成一个组件,QML语言描述 ...
- joomla3.1安装不通过Magic Quotes GPC解决方法
测试安装下joomla 3.1稳定版,但是不能成功,Magic Quotes GPC始终显示 否红色,这样就安装不了了! 要解决这个很简单,开启Magic Quotes GPC就行了,于是找到php. ...
- Unity3D 纹理偏移(TextureOffset)浅析
首先,给出圣典的解释: Material.mainTextureOffset 主纹理偏移量 var mainTextureOffset : Vector2 Description描述 The text ...
- node生成自定义命令(yargs/commander)
第一部分可以生成一个自定义命令,例如常见的”express”,yargs和commander则可以在生成的自定义命令上做扩展,yargs将命令扩展成类似express --l xx的形式;而comma ...