使用 .Net Core 對 MongoDB 的CRUD

這篇文章主要是介紹以C#強型別使用Mongodb driver連線的CRUD語法,一些MongoDB的名詞就不會多著墨。

情境

我們要建立一個 hellomongodb 的資料庫,裡面有 users 的 collection,存放 user 的相關資訊。
以下範例都會使用非同步的方式,若有需要同步執行的,可以自行移除async看看,大致上都是這樣。

先打開shell模式建立DB與collection

1
2
3
4
//切換至 hellomongodb 資料庫
use hellomongodb
//建立名為 users 的 collection
db.createCollection("users")

建立連線

1
2
3
4
5
6
const string MongoAddress = "mongodb://localhost:27017";
const string HelloDatabase = "hellomongodb";
const string UserCollection = "users";

var client = new MongoClient(MongoAddress);
var collection = client.GetDatabase(HelloDatabase).GetCollection<UserEntity>(UserCollection);

Create

剛開始肯定沒有資料的,所以我們會先建立幾筆資料做為測試

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//建立一筆資料
private static async void CreateUser()
{
await GetUsersCollection().InsertOneAsync(
new UserEntity{ Name = "Shaka", Country = "Unknown", City = "Zodiac Temple"}
);
}
//一次建立多筆資料
private static async void CreateMultiUsers()
{
await GetUsersCollection().InsertManyAsync(new List<UserEntity>
{
new UserEntity{ Name = "Jack", Country = "Taiwan", City = "Taipei"},
new UserEntity{ Name = "Sion", Country = "Unknown", City = "Underworld"},
new UserEntity{ Name = "Saga", Country = "Unknown", City = "Zodiac Temple"}
}
);
}

Read

1
2
3
4
5
6
7
8
9
10
11
12
private static async Task<List<UserEntity>> GetAllUsers()
{
var result = await GetUsersCollection().FindAsync(FilterDefinition<UserEntity>.Empty).Result.ToListAsync();
return result;
}
//尋找 name 欄位等於參數的
private static async Task<List<UserEntity>> GetUser(string name)
{
var filter = Builders<UserEntity>.Filter.Eq("name", name);
var result = await GetUsersCollection().FindAsync(filter).Result.ToListAsync();
return result;
}

Update

這個範例是尋找名稱為 name 的使用者,將他的 city 欄位改為 newCity

1
2
3
4
5
6
7
private static async Task<bool> UpdateCity(string name, string newCity)
{
var filter = Builders<UserEntity>.Filter.Eq("name", name);
var update = Builders<UserEntity>.Update.Set("city", newCity);
var result = await GetUsersCollection().UpdateOneAsync(filter, update);
return result.IsAcknowledged;
}

Delete

1
2
3
4
5
6
7
8
9
10
11
private static async Task<bool> DeleteAll()
{
var result = await GetUsersCollection().DeleteManyAsync(FilterDefinition<UserEntity>.Empty);
return result.IsAcknowledged;
}
private static async Task<bool> DeleteOne(string name)
{
var filter = Builders<UserEntity>.Filter.Eq("name", name);
var result = await GetUsersCollection().DeleteOneAsync(filter);
return result.IsAcknowledged;
}

最基本的CRUD大致上就是這樣,之後再介紹進階的用法,例如projection或是upsert等。

本篇文章完整的範例專案在這邊可以下載到。
本篇文章完整的範例專案在這邊可以下載到。

Reference

  • 作者: MingYi Chou
  • 版權聲明: 轉載不用問,但請註明出處!本網誌均採用 BY-NC-SA 許可協議。