https://docs.mongodb.com/getting-started/csharp/query/

Overview

You can use the Find and FindAsync methods to issue a query to retrieve data from a collection in MongoDB.

All queries in MongoDB have the scope of a single collection.

Queries can return all documents in a collection or only the documents that match a specified filter or criteria.

You can specify the filter or criteria in a BsonDocument and pass as a parameter to the Find andFindAsync methods.

The FindAsync method returns query results in a IAsyncCursor, which is an iterable object that yields documents.

The Find method returns a IFindFluent object.

You can use the ToListAsync method to return the results as a list that contains all the documents returned by the cursor.

ToListAsync requires holding the entire result set in memory.

Prerequisites

The examples in this section use the restaurants collection in the test database.

For instructions on populating the collection with the sample dataset, see Import Example Dataset.

Follow the Connect to MongoDB step to connect to a running MongoDB instance and declare and define the variable _database to access the test database.

Include the following using statements.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using MongoDB.Bson;

The examples use FluentAssertions to test the results.

If you are not using FluentAssertions, omit the using FluentAssertions; statement and the FluentAssertions test code below.

Query for All Documents in a Collection

To return all documents in a collection, call the FindAsync method with an empty filter document.

For example, the following operation queries for all documents in the restaurants collection.

 private async void Query()
{
var count = 0;
var collection = MongoDatabase.GetCollection<BsonDocument>(collectionName);
var filter = new BsonDocument(); var cursor = await collection.FindAsync(filter);
while (await cursor.MoveNextAsync())
{
var bacth = cursor.Current;
foreach (var document in bacth)
{
count++;
//process document
}
}
Console.WriteLine($@"{nameof(count)}={count}");
}

  

Optional.

The following code uses FluentAssertions to test the results.

If you are not usingFluentAssertions, omit.

count.Should().Be(25359);

If you have inserted, modified, or removed documents, such as specified in the other sections of the Getting Started guide, your count may differ.

The result set contains all documents in the restaurants collection.

Specify Equality Conditions

With the C# MongoDB driver, you can use the FilterDefinitionBuilder to implement the filter document.

For example, FilterDefinitionBuilder provides an Eq method to implement a filter document that specifies an equality condition:

var filter = Builders<BsonDocument>.Filter.Eq(<field>, <value>);

If the <field> is in an embedded document or an array, use dot notation to access the field.

Query by a Top Level Field

The following operation finds documents whose borough field equals "Manhattan".

 private async void QueryTopLevelField()
{
var filter = Builders<BsonDocument>.Filter.Eq("borough", "Manhattan");
var result = await collection.Find(filter).ToListAsync();
}

Optional.

The following code uses FluentAssertions to test the results.

If you are not usingFluentAssertions, omit.

result.Count().Should().Be(10259);

If you have inserted, modified, or removed documents, such as specified in the other sections of the Getting Started guide, your count may differ.

Specify Conditions with Operators

Greater Than Operator ($gt)

Less Than Operator ($lt)

Combine Conditions

You can combine multiple query conditions in logical conjunction (AND) and logical disjunctions (OR).

Logical AND

You can specify a logical conjunction (AND) for a list of query conditions by joining the conditions with an ampersand (e.g. &).

var collection = _database.GetCollection<BsonDocument>("restaurants");
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq("cuisine", "Italian") & builder.Eq("address.zipcode", "10075");
var result = await collection.Find(filter).ToListAsync();

Optional. The following code uses FluentAssertions to test the results. If you are not usingFluentAssertions, omit.

result.Count().Should().Be(15);

If you have inserted, modified, or removed documents, such as specified in the other sections of the Getting Started guide, your count may differ.

The result set includes only the documents that matched all specified criteria.

Logical OR

Sort Query Results

Additional Information

Find or Query Data with C# Driver的更多相关文章

  1. Find or Query Data with the mongo Shell

    https://docs.mongodb.com/getting-started/shell/query/ Overview You can use the find() method to issu ...

  2. Use SQL to Query Data from CDS and Dynamics 365 CE

    from : https://powerobjects.com/2020/05/20/use-sql-to-query-data-from-cds-and-dynamics-365-ce/ Have ...

  3. Insert Data with C# Driver

    https://docs.mongodb.com/getting-started/csharp/insert/ OverView You can use the InsertOneAsync meth ...

  4. Accessing data in Hadoop using dplyr and SQL

    If your primary objective is to query your data in Hadoop to browse, manipulate, and extract it into ...

  5. spark - tasks is bigger than spark.driver.maxResultSize

    Error ERROR TaskSetManager: Total size of serialized results of 8113 tasks (1131.0 MB) is bigger tha ...

  6. Architecture of Device I/O Drivers, Device Driver Design

    http://www.kalinskyassociates.com/Wpaper4.html Architecture of Device I/O Drivers Many embedded syst ...

  7. Query classification; understanding user intent

    http://vervedevelopments.com/Blog/query-classification-understanding-user-intent.html What exactly i ...

  8. Big Data Analytics for Security(Big Data Analytics for Security Intelligence)

    http://www.infoq.com/articles/bigdata-analytics-for-security This article first appeared in the IEEE ...

  9. Coursera, Big Data 3, Integration and Processing (week 1/2/3)

    This is the 3rd course in big data specification courses. Data model reivew 1, data model 的特点: Struc ...

随机推荐

  1. ASP.NET-SOAP、UDDI知识点

    1. 什么是SOAP? 答:是简单访问协议.是在分布式环境中,交换信息并实现远程调用的协议.是一个基于XML的协议.使用SOAP,可以不考虑任何传输协议,但通常还是HTTP协议,可以允许任何类型的对象 ...

  2. MRv2 工作机制 、 公平调度器、MR压缩、边数据

    对于节点数超过 4000 的大型集群,前一节描述的 MapReduce 系统开始面临着扩展的瓶颈. 2010 年 Yahoo 的团队开始设计下一代的 MapReduce. (Yet Another R ...

  3. cocos2dx-3.0创建Android项目时遇到的错误。

    cocos run -p android出现 文件名称.文件夹名或卷标语法不对 Updated project.properties Updated local.properties Updated ...

  4. intellij idea 13&amp;14 插件推荐及高速上手建议 (已更新!)

    早些年 在外企的时候,公司用的是intellij idea ,当时也是从eclipse.MyEclipse转过去的非常是不习惯. 用了一周明显感觉爱上它了.由于它非常智能,并且能纠正你非常多不好的习惯 ...

  5. hdoj 4548 美素数 【打表】

    另类打表:将从1到n的满足美素数条件的数目赋值给prime[n],这样最后仅仅须要用prime[L]减去prime[R-1]就可以: 美素数 Time Limit: 3000/1000 MS (Jav ...

  6. Android语音播报、后台播报、语音识别

    Android语音播报.后台播报.语音识别 本文介绍使用讯飞语音实现语音播报.语音识别功能. 讯飞开放平台:http://www.xfyun.cn/index.php/default/index 程序 ...

  7. 虚拟化技术对照:Xen vs KVM

    恒天云:http://www.hengtianyun.com/download-show-id-68.html 一.说明 本文主要从功能方面和性能方面对Xen和KVM对照分析,分析出其优缺点指导我们恒 ...

  8. BZOJ 1057: [ZJOI2007]棋盘制作 悬线法求最大子矩阵+dp

    1057: [ZJOI2007]棋盘制作 Description 国际象棋是世界上最古老的博弈游戏之一,和中国的围棋.象棋以及日本的将棋同享盛名.据说国际象棋起源于易经的思想,棋盘是一个8*8大小的黑 ...

  9. 安卓 使用Gradle生成正式签名apk文件

    1. 进入app中的build.gradle下面进行配置 2.进入Gradle下面选择clean和assembleRelese,双击 3.生成成功,前往查看 4.加密更安全

  10. [jzoj 5178] [NOIP2017提高组模拟6.28] So many prefix? 解题报告(KMP+DP)

    题目链接: https://jzoj.net/senior/#main/show/5178 题目: 题解: 我们定义$f[pos]$表示以位置pos为后缀的字符串对答案的贡献,答案就是$\sum_{i ...