Find or Query Data with C# Driver
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的更多相关文章
- 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 ...
- 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 ...
- Insert Data with C# Driver
https://docs.mongodb.com/getting-started/csharp/insert/ OverView You can use the InsertOneAsync meth ...
- 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 ...
- 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 ...
- Architecture of Device I/O Drivers, Device Driver Design
http://www.kalinskyassociates.com/Wpaper4.html Architecture of Device I/O Drivers Many embedded syst ...
- Query classification; understanding user intent
http://vervedevelopments.com/Blog/query-classification-understanding-user-intent.html What exactly i ...
- 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 ...
- 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 ...
随机推荐
- dubbo 部分 配置的关系-dubbo github 官方案例
1.dubbo 有一个 dubbo.properties 作为默认配置 默认配置可以在不添加新的配置的前提下使用dubbo dubbo.properties 的内容(来自 https://github ...
- cocos2d-js 热更新具体解释(一)
本文将会具体解说cocos2d-js下的热更新机制.这篇内容先给大家介绍一下两个manifest文件就当热身了. 首先介绍project.manifest: 举个样例 { "package ...
- PostgreSQL hstore 列性能提升一例
PostgreSQL 支持hstore 来存放KEY->VALUE这类数据, 事实上也相似于ARRAY或者JSON类型. 要高效的使用这类数据,当然离不开高效的索引.我们今天就来看看两类不同的 ...
- win10+ubuntu双系统卸载ubuntu
进入win10下载EasyUEFI,删除ubuntu的引导项.重启如果直接进入了win10,表示卸载成功了.然后可以格式化ubuntu的分区.
- bzoj1045: [HAOI2008] 糖果传递(数论)
1045: [HAOI2008] 糖果传递 题目:传送门(双倍经验3293) 题解: 一开始想着DP贪心一顿乱搞,结果就GG了 十分感谢hzwer大佬写的毒瘤数论题解: 首先,最终每个小朋友的糖果数量 ...
- windows模式编译
//预编译,linker链接,Windows模式#pragma comment(linker,"/subsystem:\"windows\" /entry:\" ...
- POJ 3278 Catch That Cow【BFS】
题意:给出n,k,其中n可以加1,可以减1,可以乘以2,问至少通过多少次变化使其变成k 可以先画出样例的部分状态空间树 可以知道搜索到的深度即为所需要的最小的变化次数 下面是学习的代码----@_@ ...
- C++调用约定和名字约定 thiscall
调用约定: __cdecl __fastcall与 __stdcall,三者都是调用约定(Calling convention),它决定以下内容:1)函数参数的压栈顺序,2)由调用者还是被调用者把参数 ...
- js的onclick和jq的click以及on和bind的区别
onclick和click,只能静态绑定点击事件:bind的可以一次绑定多个事件(click/onmouseover等):on可以动态的绑定事件,当页面加载完成调用on即可
- jQuery基本操作以及与js的一些比较
jQuery和js主要区别在DOM操作 用jQuery必须先引进jQuery.js文件 js和jQuery写在哪: 1.标签里面 常用就是方法调用 2.写在script标签里面 3.js文件 dom操 ...