MongoDB를 C#에서 CRUD 형태로 조작해보는 간단한 샘플 예제이다. Visual Studio 2019에서 .NET Core 콘솔 프로젝트를 생성하고 Nuget에서 MongoDB.Driver 패키지를 추가한다. 대상 프레임워크는 3.1이며 Visual Studio 버전은 16.5.3이다.
BoardModel.cs
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace ConsoleMongo
{
//[BsonIgnoreExtraElements]
public class BoardModel
{
[BsonId]
//[BsonIgnoreIfDefault]
[BsonElement("_id")]
public ObjectId ID { get; set; }
public string UserID { get; set; }
public string UserName { get; set; }
//[BsonElement("userkind")]
public string UserKind { get; set; }
public AddressModel Address { get; set; }
}
public class AddressModel
{
public string StreetAddress { get; set; }
public string ZipCode { get; set; }
}
}
MongoCRUD.cs
using MongoDB.Bson;
using MongoDB.Driver;
using System.Collections.Generic;
namespace ConsoleMongo
{
public class MongoCRUD
{
private readonly IMongoDatabase db;
public MongoCRUD()
{
var client = new MongoClient(@"mongodb://아이디:패스워드@192.168.1.33:27017/testdb");
db = client.GetDatabase("testdb");
}
// insert
public void InsertRecord<T>(string table, T record)
{
var collection = db.GetCollection<T>(table);
collection.InsertOne(record);
}
// select list
public List<T> LoadRecord<T>(string table)
{
var collection = db.GetCollection<T>(table);
return collection.Find(new BsonDocument()).ToList();
}
// select one field
public T LoadRecordById<T>(string table, string userID)
{
var collection = db.GetCollection<T>(table);
var filter = Builders<T>.Filter.Eq("UserID", userID);
return collection.Find(filter).First();
}
// insert, update
public void UpsertRecord<T>(string table, ObjectId id, T record)
{
var collection = db.GetCollection<T>(table);
collection.ReplaceOne(new BsonDocument("_id", id), record, new ReplaceOptions { IsUpsert = true });
}
// delete
public void DeleteRecord<T>(string table, ObjectId id)
{
var collection = db.GetCollection<T>(table);
var filter = Builders<T>.Filter.Eq("_id", id);
collection.DeleteOne(filter);
}
}
}
Program.cs
using System;
namespace ConsoleMongo
{
internal class Program
{
private static void Main()
{
MongoCRUD db = new MongoCRUD();
// Insert One
db.InsertRecord("board", new BoardModel { UserID = "1004", UserName = "가나닭", UserKind = "C" });
// Insert Embedded Documents
BoardModel board = new BoardModel
{
UserID = "1003",
UserName = "홍길북",
UserKind = "D",
Address = new AddressModel
{
StreetAddress = "서울특별시",
ZipCode = "12345"
}
};
db.InsertRecord("board", board);
// Upsert
var upsertRec = db.LoadRecordById<BoardModel>("board", "1003");
upsertRec.UserKind = "A";
upsertRec.Address = new AddressModel
{
StreetAddress = "서울특별시",
ZipCode = "12345"
};
db.UpsertRecord("board", upsertRec.ID, upsertRec);
// Delete
var deleteRec = db.LoadRecordById<BoardModel>("board", "1004");
db.DeleteRecord<BoardModel>("board", deleteRec.ID);
// Select list
var recs = db.LoadRecord<BoardModel>("board");
foreach (var item in recs)
{
Console.WriteLine($"{item.UserID}: {item.ID}, {item.UserName}, {item.UserKind}");
if (item.Address != null)
{
Console.WriteLine($"{item.Address.StreetAddress}, {item.Address.ZipCode}");
}
}
// Select One Field (by UserID)
var oneRec = db.LoadRecordById<BoardModel>("board", "1003");
Console.WriteLine($"{oneRec.UserID}: {oneRec.ID}, {oneRec.UserName}, {oneRec.UserKind}");
if (oneRec.Address != null)
{
Console.WriteLine($"{oneRec.Address.StreetAddress}, {oneRec.Address.ZipCode}");
}
}
}
}
Sequence Field
db.counters.insert(
{
_id: "userid",
seq: 0
}
)
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
db.users.insert(
{
_id: getNextSequence("userid"),
name: "Sarah C."
}
)
// getDate
new Date().toLocaleDateString('ko-KR').replace('x', 'y')
// getDateString
function GetDate() {
return new Date(+new Date() + 3240 * 10000).toISOString().replace("T", "").replace("Z", "").replace(/-/g, "").replace(/:/g, "").replace(/\./g, "") + Math.floor((Math.random() * (999 - 100) + 100));
}