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. java实例化对象的五种方法

    1.用new语句创建对象,这是最常见的创建对象的方法. 2.通过工厂方法返回对象,如:String str = String.valueOf(23); 3.运用反射手段,调用java.lang.Cla ...

  2. Java 学习(10):java 异常处理

    java 异常处理 异常发生的原因有很多,通常包含以下几大类: 用户输入了非法数据. 要打开的文件不存在. 网络通信时连接中断,或者JVM内存溢出. 三种类型的异常: 检查性异常: 最具代表的检查性异 ...

  3. Winserver服务器-AD字段对照简图

    AD字段对照简图

  4. Java String内存释放

    Java String内存释放 这是一个坑,Java对于String对象,不进行内存的回收: 处理大数据量的时候,少用String. 与JDK有关系:jdk1.6环境下,内存只占用10M,jdk1.8 ...

  5. MySQL优化之——集群搭建步骤具体解释

    转载请注明出处:http://blog.csdn.net/l1028386804/article/details/46833179 1 概述 MySQL Cluster 是MySQL 适合于分布式计算 ...

  6. C++_关于const 的全面总结

    C++中的constkeyword的使用方法很灵活.而使用const将大大改善程序的健壮性.本人依据各方面查到的资料进行总结例如以下,期望对朋友们有所帮助. Const 是C++中经常使用的类型修饰符 ...

  7. Hadoop解析--MapReduce

    从本篇博客開始咱们一起来具体了解Hadoop的每一个部分.我们在上篇博客中介绍了HDFS,MapReduce,MapReduce为了更有效率事实上是建立在HDFS之上的.有了分布式的文件系统,我们就能 ...

  8. iOS开发之十万个为什么&lt;1&gt;

    郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. 假设文章对您有所帮助.欢迎给作者捐赠,支持郝萌主,捐赠数额任意,重在心意^_^ 我要捐赠: 点击捐赠 Cocos2d-X源代码下载:点我传送 游戏官方下 ...

  9. 51nod 1572 宝岛地图 (预处理四个方向的最大步数优化时间,时间复杂度O(n*m+k))

    题目: 这题如果没有时间限制的话暴力可以解,暴力的话时间复杂度大概是O(k*n),1s的话非常悬. 所以我们需要换个思路,我们对每个点预处理四个方向最多能走的步数,这个预处理时间复杂度是O(n*m). ...

  10. 优化长的switch语句

    突然想到之前碰到的一个优化的面试题,现在想想switch用的太傻 public enum FormatType { GetKey, GetValue } public class Format { p ...