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 ...
随机推荐
- 创业笔记-Node.js入门之阻塞与非阻塞
阻塞与非阻塞 正如此前所提到的,当在请求处理程序中包括非阻塞操作时就会出问题.但是,在说这之前,我们先来看看什么是阻塞操作. 我不想去解释“阻塞”和“非阻塞”的具体含义,我们直接来看,当在请求处理程序 ...
- HDU 4301 Contest 1
开始时设的是第一.二行前i,j列有k种的方法数,但是,这根本转移不了--! 难点在于1,2行的讨论啊... 设f[i][j][0]为前i列分成j个部分,且第i列的两个为同一部分的方法数. f[i][j ...
- Oracle_角色_权限具体说明
一.Oracle内置角色connect与resource的权限 grant connect,resource to user; CONNECT角色: --是授予终于用户的典型权利,最主要的 ALT ...
- cocos2d-x 2.2.2 在lua中更换CCSprite的图片
废话不多说,直接上代码 --lua --获取场景 local scene= CCDirector:sharedDirector():getRunningScene() --创建精灵 local tes ...
- xBIM 基础05 3D墙案例
系列目录 [已更新最新开发文章,点击查看详细] 使用编码的形式去生成一堵墙的模型需要做很多的工作. using System; using System.Collections.Generic ...
- css文字换行问题white-space:pre-line或者white-space:pre-wrap,解决word-wrap:break-word解决不了的
想让文字换行必须要写的那几个css样式就略过了.当一行文字是数字或字母时或者数字字母组合时会出现不换行局面,这时候加个word-wrap:break-word:就基本可以解决但是有种情况是它解决不了的 ...
- JS的数据类型(包含:7种数据类型的介绍、数据类型的转换、数据类型的判断)
前言 最新的 ECMAScript 标准定义了JS的 7 种数据类型,其中包括: 6 种基本类型:Boolean.Null.Undefined.Number.String.Symbol (ECMASc ...
- MyBatis数据持久化(二)建立数据库会话
上篇文章中介绍了我们使用mybatis前的准备工作,并在程序中通过jdbc与mysql数据库成功建立连接,接下来介绍如何使用mybatis与数据库建立会话.我们需要以下几个步骤: 1.在build p ...
- hdu1010 - dfs,奇偶剪枝
题目链接 给一个迷宫,问从起点到终点存不存在一条长度为T的路径. ------------------------------------------------------------------- ...
- shell编程, 100文钱买100只鸡, 简单实现
今天碰到一个有趣的问题: 群友用shell写的一个: #!/bin/bash # 百元买百鸡,每种鸡至少买一只 all= # 公鸡每只多少元 read -p '公鸡多少文一只: ' gongji # ...