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");

时间: 2024-08-25 06:47:51

mongodb driver c#语法的相关文章

MongoDB.Driver 2.4以上版本 在.NET中的基本操作

MongoDB.Driver是操作mongo数据库得驱动,最近2.0以下版本已经从GitHub和Nuget中移除了,也就是说.NET Framework4.0不再能从官方获取到MongoDB得驱动了,其次MongoDB.Driver2.0开始API变更巨大,本文不适用MongoDB.Driver2.0以下版本,亦不适用.NET Framework4.5以下版本 要在.NET中使用MongoDB,就必须引用MongoDB的驱动,使用Nuget安装MongoDB.Driver是最方便得,目前Nuge

MongoDB 3.0 关于安全认证后使用C#调用碰上“System.TimeoutException”类型的异常在 MongoDB.Driver.Core.dll 中发生的相关问题

"System.TimeoutException"类型的异常在 MongoDB.Driver.Core.dll 中发生,但未在用户代码中进行处理 操作MongoDB类库版本: ---------------------------------------------- MongoDB.Driver 2.3 MongoDB.Driver.Core 2.3 MongoDB.Bson 2.3 MongoDB 版本 3.0 连接字符串的相关变化: -----------------------

Mongodb.Driver操作MongoDB

上一篇博客主要介绍了MongoDB和它的的使用场景,这篇文章主要介绍一下如何用C#如何借助官方的Mongodb.Driver操作MongoDB 1.NuGet引入Mongodb.Dirver 安装后项目中会新增如下dll MongoDB.Driver.dll:顾名思义,驱动程序 MongoDB.Bson.dll:序列化.Json相关 2.初始化集合,子类需重写集合名 #region 构造函数 /// <summary> /// 集合 /// </summary> public st

基于MongoDB.Driver的扩展

由于MongoDB.Driver中的Find方法也支持表达式写法,结合[通用查询设计思想]这篇文章中的查询思想,个人基于MongoDB扩展了一些常用的方法. 首先我们从常用的查询开始,由于MongoDB.Driver支持类似于AutoMapper返回的指定属性(Project<TDto>方法),所以这里都是基于泛型的扩展 /// <summary> /// 同步查询指定条件的数据,并且返回指定类型TDto /// </summary> /// <typeparam

扩展 MongoDB.Driver 支持实体使用方式

一.安装 Install-Package Apteryx.MongoDB.Driver.Extend 移步我的项目https://github.com/code-institutes/Apteryx.MongoDB.Driver.Extend有详细的使用说明. 原文地址:https://www.cnblogs.com/apteryx/p/10818941.html

Java MongoDB Driver 3.x - Quickly Start

Maven Dependency: <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.2.2</version> </dependency> Make a Connection The following example shows five ways to conn

通过php的MongoDB driver连接Azure的DocumentDB PaaS

Azure的DocumentDB是NoSQL类型的数据库.它还可以和目前流行的mongodb兼容,采用mongodb的driver可以直接连接Azure的DucumentDB. 目前在国内的Azure上,DocumentDB已经正式商用了,兼容mongodb的版本目前还在preview阶段. 本文将介绍如何创建,并通过php的mongodb的driver连接documentDB. 一 在Azure的管理界面上创建DocumentDB: 1 点击portal左上角的"+"号,然后输入do

Mongodb的基本语法

前段时间工作上面由于没有多少事所以玩了玩mongodb,学习了它的基本语法,然后现在在这里做一个简单的总结. 1.我是在win平台上面,启动的话比较麻烦,所以我就简单的把启动过程做了个批处理文件 启动脚本 :启动mongodb的批处理文件,到mongodb的bin目录下面 D: cd "Program Files" cd MongoDB\Server\3.2\bin :其中D盘下面的data,db目录是自己手动创建的 :启动带有的参数 --auth(开启用户访问权限) :--dbpat

mongodb查询的语法(大于,小于,大于或等于,小于或等于等等)

1 ) . 大于,小于,大于或等于,小于或等于 $gt:大于$lt:小于$gte:大于或等于$lte:小于或等于 例子: db.collection.find({ "field" : { $gt: value } } ); // greater than : field > valuedb.collection.find({ "field" : { $lt: value } } ); // less than : field < valuedb.coll