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. Docker 管理工具的选择:Kubernetes 还是 Swarm?

    [编者的话]选择Kubernetes 或者 Swarm 就像在将 Linux 桌面发行版的范围缩小到两个后选出一个最喜欢的.哪个更满足你的需要如何才是决定因素. [3 天烧脑式基于Docker的CI/ ...

  2. oracle间隔分区

    http://blog.csdn.net/rznice/article/details/55048876

  3. Cocos结构

    基类:CApplicationProtocol 纯虚函数virtual bool applicationDidFinishLaunching() = 0; CCApplication继承于CCAppl ...

  4. HD-ACM算法专攻系列(9)——大菲波数

    题目描述: 源码: 运用Java大数求解. import java.math.BigInteger; import java.util.*; public class Main { //主函数 pub ...

  5. Aspose.Words 操作指北

    前言:   这段时间因为业务需求,需要做一个word 导出,表单式的那种,因为之前也做过NPOI 操作 Excel 这类型的问题,所以总以为word 导出应该挺简单的,一直没有研究这块,汗颜,天真大意 ...

  6. 脱离node自己使用普通的requirejs管理js资源

    首先,工程目录: 现在主页面(web框架写法.html): <!DOCTYPE html> <html lang="en"> <head> &l ...

  7. Html表单提交到Servlet输出到页面乱码

    Html使用的编码是UTF-8编码显示页面,之后使用form表单提交字段到Servlet中,Servlet将利用getParamer方法获得form提交的字段,之后通过Respone中的writer将 ...

  8. UVa 12545 Bits Equalizer【贪心】

    题意:给出两个等长的字符串,0可以变成1,?可以变成0和1,可以任意交换s中任意两个字符的位置,问从s变成t至少需要多少次操作 先可以画个草图 发现需要考虑的就是 1---0 0---1 ?---0 ...

  9. CF 286(div 2) B Mr. Kitayuta's Colorful Graph【传递闭包】

    解题思路:给出n个点,m条边(即题目中所说的两点之间相连的颜色) 询问任意两点之间由多少种不同的颜色连接 最开始想的时候可以用传递闭包或者并查集来做,可是并查集现在还不会做,就说下用传递闭包来做的这种 ...

  10. HTML、CSS规范

    作为一名前端开发者,至少要对HTML.CSS规范有个了解,然后尝试在项目是使用,以便别人阅读你代码的时候,也相对轻松点. HTML.CSS规范,参见:编码规范 by @mdo JavaScript 参 ...