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
相关文章
- Starting with Keras.NET in C# - Train Your First Model
- 【c#】我们为什么要用 yield return
- Insert Data with C# Driver
- Versioning with the Override and New Keywords (C# Programming Guide)
- C#中的转换
- c# 中内部类的简单介绍 C#内部类
- c#代码 天气接口 一分钟搞懂你的博客为什么没人看 看完python这段爬虫代码,java流泪了c#沉默了 图片二进制转换与存入数据库相关 C#7.0--引用返回值和引用局部变量 JS直接调用C#后台方法(ajax调用) Linq To Json SqlServer 递归查询
- C#订阅与发布标准实现 visual studio code .net 开发 设计模式之☞策略模式 C#字符串转二进制、二进制转字符串 c# 接口的协变和逆变 c# 使用迭代器来创建可枚举类型 博客园首页新随笔联系订阅管理 随笔 - 117 文章 - 0 评论 - 57 c# 创建,加载,修改XML文档
- 如何使用T-SQL备份还原数据库及c#如何调用执行? C#中索引器的作用和实现。 jquery控制元素的隐藏和显示的几种方法。 localStorage、sessionStorage用法总结 在AspNetCore中扩展Log系列 - 介绍开源类库的使用(一) span<T>之高性能字符串操作实测
- c#封装DBHelper类 c# 图片加水印 (摘)C#生成随机数的三种方法 使用LINQ、Lambda 表达式 、委托快速比较两个集合,找出需要新增、修改、删除的对象 c# 制作正方形图片 JavaScript 事件循环及异步原理(完全指北)
- XML序列化 判断是否是手机 字符操作普通帮助类 验证数据帮助类 IO帮助类 c# Lambda操作类封装 C# -- 使用反射(Reflect)获取dll文件中的类型并调用方法 C# -- 文件的压缩与解压(GZipStream)
- 反爬虫:利用ASP.NET MVC的Filter和缓存(入坑出坑) C#中缓存的使用 C#操作redis WPF 控件库——可拖动选项卡的TabControl 【Bootstrap系列】详解Bootstrap-table AutoFac event 和delegate的分别 常见的异步方式async 和 await C# Task用法 c#源码的执行过程
- c#打包文件解压缩 C#中使用委托、接口、匿名方法、泛型委托实现加减乘除算法 一个简单例子理解C#的协变和逆变 对于过长字符串的大小比对
- 利用反射快速给Model实体赋值 使用 Task 简化异步编程 Guid ToString 格式知多少?(GUID 格式) Parallel Programming-实现并行操作的流水线(生产者、消费者) c# 无损高质量压缩图片代码 8种主要排序算法的C#实现 (一) 8种主要排序算法的C#实现 (二)
- C#字符串数组排序 C#排序算法大全 C#字符串比较方法 一个.NET通用JSON解析/构建类的实现(c#) C#处理Json文件 asp.net使用Jquery+iframe传值问题
- Word控件Spire.Doc 转换教程(二十六):在 C#、VB.NET 中将 Word 转换为 EPUB 时添加封面图片
- C#【中级篇】 C# 方法
- C#,码海拾贝(08)——埃特金(Aitken)逐步曲线插值算法,《C#数值计算算法编程》源代码升级改进版
- C# http 发送文件和接收文件的代码。
- C#关键字var是什么,在何种情况下使用
- c# 定制Equals()
- 基于人脸识别的考勤系统 — Flask App — With GUI — with source code
- 用c#开发微信 (22) 微信商城 - 微信支付 (c#源码)
- C# OleDb判断ACCESS中是否存在表,不存在则新建
- 【Unity3D日常开发】Unity3D中 C#反射Reflection的使用
- c# 单实例运行
- C# 之 结构体详解
- Tutorial: Getting Started with SignalR (C#) -摘自网络
- C#实现RSA签名及认证
- C#-TimeSpan-计算时间差
- c# 并行计算(大量循环处理的场景下)