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 ...
随机推荐
- Lock-less and zero copy messaging scheme for telecommunication network applications
A computer-implemented system and method for a lock-less, zero data copy messaging mechanism in a mu ...
- Linux下基于多线程的echo
准备开始写一些Linux 下网络编程以及多线程的blog,就从这个简单的echo程序开始吧. 在echo的服务端使用多线程与客户进行通信,可以实现一个服务端程序同时连接多个客户的功能.那么,到底在服务 ...
- struts.xml中出现extends undefined package struts-default解决的方法
在struts.xml中出现extends undefined package struts-default,经过查阅资料原来是由于没有联网的缘故. 这样解决:在myeclipse中关联本地的dtd文 ...
- C++ OTL MySQL(Windows/Linux) V8.1
Windows每秒钟10000条以上插入:Linux每秒插入300条以上.Q269752451 输出截图: Linux输出: Windows输出: 有须要的联系 QQ 3508551694 water ...
- 认识一下Kotlin语言,Android平台的Swift
今天在CSDN首页偶然看到一个贴子JetBrains正式公布Kotlin 1.0:JVM和Android上更好用的语言 看完后,感觉Kotlin语法非常简洁,有一系列动态语言的特点,Lambda表达式 ...
- Forms authentication timeout vs sessionState timeout
https://stackoverflow.com/questions/17812994/forms-authentication-timeout-vs-sessionstate-timeout Th ...
- 指向类成员函数的函数指针及#define typedef 实现类成员函数的类型转换
#include <iostream> using namespace std; class Test { public : void print() { cout << &q ...
- ubuntu下创建文件夹快捷方式
title: ubuntu下创建文件夹快捷方式 toc: false date: 2018-09-01 17:22:28 categories: methods tags: ubuntu 快捷方式 s ...
- linux系统定时任务crond入门
1,Crond: Crond是linux系统中用来定期执行命令或指定程序任务的一种服务或者软件.(Centos5以后默认存在) 当优化开机自启动的时候,第一个就是crond. Crond服务默认情况( ...
- Codeforces 982 B. Bus of Characters(模拟一个栈)
解题思路: 排序之后模拟一个栈(也可以用真的栈),时间复杂度o(n). 代码: #include <bits/stdc++.h> using namespace std; typedef ...