---
# System prepended metadata

title: MongoDB
tags: [Code, C#, MongoDB]

---

# MongoDB
[Toc]
## C# 開發
### 相關 using
```
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
```
### 泛型 T DBModel 繼承 BaseMongoDBModel
所有的 Model 都需要繼承 BaseMongoDBModel
```
public class BaseMongoDBModel
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    [JsonIgnore]
    public ObjectId _id { get; set; }
    [BsonIgnore]
    public string Id 
    { 
        get 
        { 
            return _id.ToString(); 
        } 
    }
}
```
### 連線初始化

```
private IMongoClient _mongoClient;
private IMongoDatabase _mongoDatabase;
public IMongoCollection<T> _Collection;
public static string _tableName = typeof(T).Name.Replace("Model", string.Empty);
public BaseMongodbRepository(string connectionString, string database)
{
    // 產生 MongoClient 物件
    _mongoClient = new MongoClient(connectionString);
    // 取得 MongoDatabase 物件
    _mongoDatabase = _mongoClient.GetDatabase(database);
    // 取得 Collection
    _Collection = _mongoDatabase.GetCollection<T>(_tableName);
}
```
### 取得列表
```
public List<T> GetAll()
{
    var products = _Collection.AsQueryable().ToList();

    return products;
}
```
### 取得單筆
```
public T GetById(ObjectId id)
{
    FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);
    return _Collection.Find(filter).FirstOrDefault();
}
```
### 新增資料
```
public void Insert(T model)
{
    _Collection.InsertOne(model);
}
```
### 更新資料
```
public ReplaceOneResult Update(T entity)
{
    FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", entity.Id);

    return _Collection.ReplaceOne(filter, entity); ;
}
```
### 刪除單筆
```
public DeleteResult DeleteById(ObjectId id)
{
    FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);
    return _Collection.DeleteOne(filter);
}
```

###### tags: `Code` `C#` `MongoDB`
