mongodb driver c#语法

译:(原文地址:http://www.mamicode.com/info-detail-1400017.html)

驱动程序引入了一些与filters、updates、projections、sorts和index keys的规范相关的类型,这些类型在整个API中使用.

大部分的定义需要buliders来帮助创建对象。每个bulider都有一个泛型类型参数TDocument,它表示您正在使用的文档类型。它几乎总是与IMongoCollection中使用的通用TDocument参数相匹配。

Fields
FieldDefinition<TDocument> 和FieldDefinition<TDocument>用来定义一个Field对象。它们是隐式可转换的字符串,因此您可以简单地传递您想要的字段名。例如,要使用名为“fn”的字段,使用BsonDocument的TDocument,执行以下操作:
FieldDefinition<BsonDocument> field = "fn";
但是,如果您使用的是一个映射类,那么我们就需要定义一个与属性名相等的字符串。如下例所示:给一个Person类
class Person
{
    [BsonElement("fn")]
    public string FirstName { get; set; }

    [BsonElement("ln")]
    public string LastName { get; set; }
}
因为我们知道类型为Person,我们可以提供属性名“FirstName”,并且"fn"依然可以被使用。
FieldDefinition<Person> field = "FirstName";
注意:我们未验证所提供的字符串是否作为映射字段存在,所以仍然可以提供未映射的字段:
FieldDefinition<Person> field = "fn";
输出的字段名就仅是fn,而非映射字段

Filters
FiltersDefinition<TDocument>定义一个filter,它是由json字符串或者BsonDocument转换而来。
FilterDefinition<BsonDocument> filter = "{ x: 1 }";
// or
FilterDefinition<BsonDocument> filter = new BsonDocument("x", 1);
上边两种方式都定义了同一个filter{x:1}
FilterDefinitionBuilder<TDocument>提供了一种类型安全的API,用于构建简单和复杂的MongoDB查询。
例如,构建一个filter:{x:10,y:{$lt:20}},下边的调用时等价的:
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq("x", 10) & builder.Lt("y", 20);
注意:&运算符是重载的。
如下例:
创建一个类:
class Widget
{
    [BsonElement("x")]
    public int X { get; set; }

    [BsonElement("y")]
    public int Y { get; set; }
}
var builder = Builders<Widget>.Filter;
var filter = builder.Eq(widget => widget.X, 10) & builder.Lt(widget => widget.Y, 20);
这样做的好处是编译期运行安全,并且,你也可以进行重构。

另外,那你也可以使用field名来进行代替:
var filter = builder.Eq("X", 10) & builder.Lt("Y", 20);

// or

var filter = builder.Eq("x", 10) & builder.Lt("y", 20);
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");










  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java MongoDB DriverMongoDB 官方提供的 Java 驱动程序,用于连接和操作 MongoDB 数据库。目前最新版本为 4.x。 要下载 Java MongoDB Driver 4.x,可以按照以下步骤进行: 1. 打开 MongoDB 官网的下载页面(https://www.mongodb.com/try/download/drivers/java)。 2. 在页面中找到 Java 驱动程序部分。 3. 点击"Download"按钮,会弹出一个对话框,选择希望下载的版本和文件类型(例如 JAR 或 POM)。 4. 点击"Download"按钮下载驱动程序。 5. 下载完成后,将下载的驱动程序文件添加到你的 Java 项目中。 在使用 Java MongoDB Driver 时,需要注意以下几点: 1. 确保你的项目已经添加了正确的驱动程序依赖。如果使用 Maven 进行项目管理,可以在 pom.xml 文件中添加以下依赖项: ```xml <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.x.x</version> </dependency> ``` 2. 在代码中使用 MongoDB 驱动程序提供的 API 来连接和操作数据库。例如,可以使用以下代码来连接 MongoDB 数据库: ```java import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoDatabase; public class MongoDBExample { public static void main(String[] args) { MongoClient client = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = client.getDatabase("mydb"); // 进行数据库操作... client.close(); } } ``` 这样就完成了 Java MongoDB Driver 4.x 的下载和使用。可以根据项目的需求,使用更高级的 API 进行更丰富的 MongoDB 数据库操作。 ### 回答2: Java MongoDB DriverMongoDB 官方提供的 Java 语言的客户端驱动程序,用于与 MongoDB 数据库进行通信和交互。当前最新版本是 4.。 首先,你可以在 Maven 仓库中下载 Java MongoDB Driver 的依赖。你可以在项目的 Maven 配置文件(pom.xml)中添加如下依赖项: ```xml <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.4.0</version> </dependency> </dependencies> ``` 或者,你也可以直接在 MongoDB 官方网站的 Java Driver 下载页面上下载最新版本的 Java MongoDB Driver。下载完成后,你可以将下载的 JAR 文件添加到你的项目的类路径下。 另外,你还需要下载 MongoDB 的 Java 连接管理器(Java Connect Manager)JAR 文件,它是 MongoDB 的 Java 驱动的核心组件。你同样可以在 Maven 仓库或 MongoDB 官方网站上找到并下载到相应的版本。 一旦你下载了 Java MongoDB Driver 的 JAR 文件,你就可以将它们添加到你的 Java 项目的类路径中。然后,你可以在代码中导入相关的 MongoDB 类和方法,以便使用 Java MongoDB Driver 来连接和操作 MongoDB 数据库。 总之,要下载 Java MongoDB Driver 4.,你可以通过 Maven 仓库或者在 MongoDB 官方网站找到相关的 JAR 文件。下载完成后,将它们添加到项目类路径中,并在代码中导入相关类和方法,就可以开始使用 Java MongoDB Driver 进行数据库操作了。 ### 回答3: Java MongoDB DriverMongoDB官方提供的Java语言的驱动库,用于连接和操作MongoDB数据库。在进行Java开发时,如果需要使用MongoDB数据库,就需要下载并引入Java MongoDB Driver来实现与数据库的交互。 Java MongoDB Driver的最新版本是4.x系列。下载Java MongoDB Driver 4.x的步骤如下: 1. 打开MongoDB官方网站,进入“Connectors”页面。 2. 在Java的部分找到Java MongoDB Driver的下载链接。 3. 点击下载链接,选择适合你操作系统/开发环境的版本。 4. 下载完成后,解压下载的文件。 在项目中使用Java MongoDB Driver 4.x的步骤如下: 1. 打开你的Java项目,进入项目的构建工具配置文件(如Maven的pom.xml文件)。 2. 在依赖配置中添加MongoDB Driver的引用。 示例(Maven配置): ``` <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.4.1</version> </dependency> ``` 3. 保存并更新项目的依赖。 完成以上步骤后,你就可以在Java代码中使用Java MongoDB Driver 4.x来连接和操作MongoDB数据库了。根据具体需求,可以使用Driver提供的API进行数据的增删改查等操作。 总结:下载Java MongoDB Driver 4.x可通过MongoDB官方网站获取合适版本的驱动库,然后在项目的构建工具配置文件中添加依赖引用即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值