[MongoDB]如何查詢資料

  • 3272
  • 0
  • 2015-11-05

摘要:[EF+MongoDB]如何查詢資料

C# driver version:2.1:

ps.本文章是查詢collection裡面的資料用的,不是查詢檔案明細用的喔

0.到下面網站下載EF驗證元件,選擇dll下載並加入參考到專案即可,MongoDB官網似乎都習慣用這個元件驗證

去驗證相關的LINQ語法是否跟預期符合,而不是讓程式設計師自己寫if else, 或是try catch去驗證

記得FluentAssertions.dll, FluentAssertions.Core.dll都需要下載

http://www.fluentassertions.com/

1.下載官方提供的c#專用dll來操作MongoDB,選擇.net driver,這個package就是包山包海所有dll通包

http://mongodb.github.io/mongo-csharp-driver/

1.開一個visual studio專案, WinForm或WebForm都可,就是不要用Console, 因為MongoDb提供的強力的Async非同步function都是針對

WinForm, WebForm要強化使用者體驗而特別製作的,如果用Console請改用同步的mongoDB function喔,這邊將以官網未來的非同步方向為主。

,然後把步驟0+1下載的所有dll加入參考

 

2.確認下列有using


using System.Linq;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using FluentAssertions;
using System.IO;
using MongoDB.Driver.GridFS;

,並且初始化MongoClient(建議放在Constructor或page_load)之後才可以查詢


protected void Page_Load(object sender, EventArgs e)
{
	//此兩行初始化MongoClient, 利用client存取資料庫,建議放在Constructor
	_client = new MongoClient();
	//如果要連線到某台伺服器,像是下面這樣即可
	//_client = new MongoClient("mongodb://mydb.com.tw");
	_database = _client.GetDatabase("test");
}

2.利用以下程式碼查詢restaurant所有資料, 記得非同步的部分加上async, await關鍵字,按下F5直接按下button1按鈕即可順利執行

這邊的filter條件相當於關連式資料庫的SQL的where的and,需要更多查詢的方式(例如:or, orderby),請參閱最下方的官網超連結

.aspx需加入非同步的標頭關鍵字Async="true" 

ps.本來官網提供的


<%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="TestMongoDBWebForm.Test" %>

.aspx的 web control部分


<asp:Button ID="btnAsyncQuery" runat="server" OnClick="btnAsyncQuery_Click" Text="AsyncQuery" />
<asp:Label ID="lblAsyncQuery" runat="server" Text="lblAsyncQuery"></asp:Label>

code_behind:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using FluentAssertions;
using System.IO;
using MongoDB.Driver.GridFS;


namespace TestMongoDBWebForm
{
    public partial class Test : System.Web.UI.Page
    {

        protected static IMongoClient _client;
        protected static IMongoDatabase _database;

        protected void Page_Load(object sender, EventArgs e)
        {
            //此兩行初始化MongoClient, 利用client存取資料庫,預設連接localhost,建議放在Constructor
            _client = new MongoClient();
			//如果要連線到某台伺服器,像是下面這樣即可
			//_client = new MongoClient("mongodb://mydb.com.tw");
            _database = _client.GetDatabase("test");
        }

        protected async void btnAsyncQuery_Click(object sender, EventArgs e)
        {                       
            var collection = _database.GetCollection("restaurants");
            var filter = Builders.Filter.Eq("borough", "Manhattan");
            var result = await collection.Find(filter).ToListAsync();
            result.Count().Should().Be(10259);
            lblAsyncQuery.Text = result.Count().ToString() + "筆資料受影響";

        }

    }
}

原本implement function不應該用threading方式實做,但是官網只有提供非同步的function而已

雖然msdn非常非常不建議以同步的方式執行非同步的function,但...官網就只提供非同步function而已

如果要強制以同步的方式執行官網提供的非同步function的話,加上關鍵字Task.Run即可,範例如下:


//同步查詢
protected  void btnSyncQuery_Click(object sender, EventArgs e)
{
	var collection = _database.GetCollection("restaurants");
	var filter = Builders.Filter.Eq("borough", "Manhattan");
	var t = Task.Run(() => collection.Find(filter).ToListAsync());
	t.Result.Count().Should().Be(10259);
	lblSyncQuery.Text = t.Result.Count().ToString() + "筆資料受影響";

}

 

由於官網提供的查詢方法非常多種,先寫他示範的第一種就好,要更多的其他查詢,再上官網查....

以上內容參考官網:

Find or Query Data with C# Driver

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