mongodb driver c#語法

来源:http://www.cnblogs.com/klsw/archive/2016/06/19/5599150.html
-Advertisement-
Play Games

Definitions and BuildersThe driver has introduced a number of types related to the specification of filters, updates, projections, sorts, and index ke ...


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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • WWDC 2016 大會之後,蘋果公司發佈了四個全新平臺:iOS,macOS,watchOS 和 tvOS。並且在此之後,蘋果應用商店審核條款也同時進行了更新——貌似不算進行了更新,簡直就是重寫!上個版本的 30 個章節被修改成了 5 大章節,但原版英文版字數從 5000 多個英文單詞增加到了 60 ...
  • 一.繼承關係 二.概述 TAB的容器。這個對象包含兩個子元素: 三.常用方法 四.三個內部類 TabHost.TabSpec tab(標簽)有一個indicator,content後臺tag.例如: 1.indicator 有三個重載的方法可以設置標簽的名字和圖案。返回值都是TabHost.TabS ...
  • 便利的初始化view以及設置tag值 效果 源碼 https://github.com/YouXianMing/iOS-Project-Examples 中的 SetRect 細節 需要實現協議(用NSMapTable的strongToWeakObjectsMapTable來作為存儲string - ...
  • 【版權所有,轉載請註明出處。出處:http://www.cnblogs.com/joey-hua/p/5597818.html 】 據說安卓應用里通過fork子進程的方式可以防止應用被殺,大概原理就是子進程被殺會向父進程發送信號什麼的,就不深究了。 首先fork()函數它是一個系統調用,在sys.h ...
  • 最全面的 Android 編碼規範指南 本文word文檔下載地址:http://pan.baidu.com/s/1bXT75O 1. 前言 最全面的 Android 編碼規範指南 本文word文檔下載地址:http://pan.baidu.com/s/1bXT75O 1. 前言 這份文檔參考了 Go ...
  • 最近和幾個朋友交流Android開發中的網路下載問題時,談到了用Thread開啟下載線程時會產生的Bug,其實直接用子線程開啟下載任務的確是很Low的做法,那麼原因究竟如何,而比較高大上的做法是怎樣?於是用這篇博文詳細分析記錄一下。 一、概念介紹 Thread是指在CPU運行的一個程式中,可以有多個 ...
  • 存儲過程和存儲函數 指存儲在資料庫中供所有用戶程式調用的子程式叫存儲過程、存儲函數。 存儲過程和存儲函數的區別? 存儲函數:可以通過return 語句返回函數值。 存儲過程:不能 除此之外我們可以認為他們是完全一樣的。 存儲過程 1、創建存儲過程 用create procedure命令簡歷存儲過程。 ...
  • 需求:查詢並輸出30號部門的雇員信息 方式一:使用 loop...fetch 方式二:使用游標 for 迴圈 方式三:使用動態sql和綁定變數 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...