• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

FindorQueryDatawithC#Driver

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

https://docs.mongodb.com/getting-started/csharp/query/

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
13继续C#中的方法,带返回值的方法介绍发布时间:2022-07-14
下一篇:
C#图片识别(支持21种语言)转发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap