MongoDB 공식 C# Driver

DataBase 2014. 3. 25. 12:24

MongoDB 공식 C# Driver

  • CSharp Language Center

http://docs.mongodb.org/ecosystem/drivers/csharp/

  • CSharp Driver Tutorial

http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/#csharp-driver-tutorial

  • 1.8.1 버전 API 문서

http://api.mongodb.org/csharp/1.8.1/

 

 

접속 시 인증

 

// on the connection string

var connectionString = "mongodb://user:pwd@localhost/?safe=true";

var server = MongoServer.Create(connectionString);

   

// in code

var settings = new MongoServerSettings() {

   DefaultCredentials = new MongoCredentials("user", "pwd"),

   SafeMode = SafeMode.True

};

   

var server = MongoServer.Create(settings);

 

 

서로 인증 정보가 다른 database를 사용할 때

 

var credentialsStore = new MongoCredentialsStore();

credentialsStore.AddCredentials(

      "hr", new MongoCredentials("user1", "pwd1"));

credentialsStore.AddCredentials(

      "inventory", new MongoCredentials("user2", "pwd2"));

   

var settings = new MongoServerSettings {

      CredentialsStore = credentialsStore,

      SafeMode = SafeMode.True

};

   

var server = MongoServer.Create(settings);

 

var credentials = new MongoCredentials("user", "pwd");

var database = server.GetDatabase("hr", credentials);

 

 

Admin으로 인증하기

 

var cs = "mongodb://user(admin):pwd@localhost/?safe=true";

var server = MongoServer.Create(cs);

   

var adminCredentials = new MongoCredentials("user", "pwd", true);

var settings = new MongoServerSettings {

      DefaultCredentials = adminCredentials,

      SafeMode = SafeMode.True

};

   

var server = MongoServer.Create(settings);

 

 

시간 사용

  • 입력
     

    // 201308011121 라는 문자열로 DateTime 객체를 만든다.

    // 중요: MongoDB는 UTC date 타임대를 사용하므로 System.Globalization.DateTimeStyles.AssumeUniversal 로 조정한다

    IFormatProvider culture = new System.Globalization.CultureInfo("", true);

    DateTime date = DateTime.ParseExact(date_time, "yyyyMMddHHmm", culture, System.Globalization.DateTimeStyles.AssumeUniversal);

       

       

    var login = BasicLogDB.GetCollection<BsonDocument>("Login");

       

    BsonDocument data = new BsonDocument()

    {

       {"ID", id},

       {"UniqNum", UniqueNumber},

       {"date", date}

    };

       

    login.Insert(data);

     

 

예제 Insert

  • 기본
     

    using MongoDB.Bson;

    using MongoDB.Driver;

    using MongoDB.Driver.Builders;

       

    MongoClient cli = new MongoClient(textBoxAddress.Text);

    MongoDatabase testdb = cli.GetServer().GetDatabase("test");

       

    MongoCollection<BsonDocument> Customers = testdb.GetCollection<BsonDocument>("Account");

                   

    try

    {

      for (int i = 0; i < Count; ++i)

      {

          BsonDocument data = new BsonDocument()

          {

              {"ID", string.Format("{0}{1}",textBoxPreFix.Text, (StartIndex+i).ToString())},

              {"PW", "1111"}

          };

       

          Customers.Insert(data);

      }

    }

    catch (Exception err)

    {

       MessageBox.Show(err.ToString());

    }

  • list 자료형을 값으로 사용 할 때
     

    List<int> userCount = new List<int>();

       

    BsonDocument insertData = new BsonDocument()

    {

        {"UserCount", new BsonArray(userCount)},

        {"date", datetime}

    };

       

    collection = dbLib.dataMiningLogDB.GetCollection<BsonDocument>("DailyHourLoginUserCount");

     

 

예제 Select

  • 하나만 반환
     

    public static bool Auth(string id, string pw)

    {

       MongoClient cli = new MongoClient("mongodb://17.20.30.21");

       MongoDatabase database = cli.GetServer().GetDatabase("test");

       var Accounts = database.GetCollection<BsonDocument>("Account");

       

       IMongoQuery query = Query.EQ("ID", id);

       var result = Accounts.Find(query).SingleOrDefault();

                   

       if (result == null)

       {

          return false;

       }

       

       if (result["PW"] != pw)

       {

          return false;

       }

       

      return true;

    }

  • 여러개 반환
     

    IMongoQuery query = Query.EQ("version", version);

    var results = ItemInfo.Find(query);

       

       

    List<ItemInfo> itemlist = new List<ItemInfo>();

       

    foreach (var iteminfo in results)

    {

       var item = new ItemInfo

       {

          version = version,

          ID = iteminfo["ID"].AsInt32,

          name = iteminfo["name"].AsString,

          Lv = iteminfo["Lv"].AsInt32

       };

       

       itemlist.Add(item);

    }

    //

    public class ItemInfo

    {

       public int version;

       public int ID;

       public string name;

       public int Lv;

    }

  • Where절 사용
     

    Query<Employee>.Where(d => d.EmployeeNumber == 1234)

    Query<Employee>.Where(d => d.Name == "John Doe")

    Query<Employee>.Where(d => d.EmployeeStatus != Status.Active)

    Query<Employee>.Where(d => d.Salary > 100000)

  • 복합 쿼리
     

    var query = Query.GTE("x", 1).LTE(3);

    // becomes

    var query = Query.And(Query.GTE("x", 1), Query.LTE("x", 3));

       

    var query = Query.Not("x").GT(1);

    // becomes

    var query = Query.Not(Query.GT("x", 1));

       

    var query = Query.Exists("x", true);

    // becomes

    var query = Query.Exists("x");

       

    var query = Query.Exists("x", false);

    // becomes

    var query = Query.NotExists("x");

  • 해당 collection 모든 데이터 가져오기
     

    List<AccountData> lstAccount = new List<AccountData>();

       

    MongoClient cli = new MongoClient("mongodb://172.20.60.221");

    MongoDatabase database = cli.GetServer().GetDatabase("WebTest");

    var Accounts = database.GetCollection<BsonDocument>("Account");

       

    // query문 없이 FindAll 사용, 해당 collection에 모든 데이터를 가져올 수 있다.           

    var result = Accounts.FindAll();

       

    foreach (var AccountInfo in result)

    {

        var Account = new AccountData

        {

            AccountID = AccountInfo["ID"].AsString,

            PassWord = AccountInfo["PW"].AsDouble

        };

    }

    return lstAccount;

     

 

예제 Update, Delete

 

// http://www.csharpstudy.com/Tips/Tips-mongodb.aspx

// Mongo DB를 위한 Connection String

string connString = "mongodb://localhost";

   

// MongoClient 클라이언트 객체 생성

MongoClient cli = new MongoClient(connString);

   

// testdb 라는 데이타베이스 가져오기

// 만약 해당 DB 없으면 Collection 생성시 새로 생성함

MongoDatabase testdb = cli.GetServer().GetDatabase("testdb");

   

// testdb 안에 Customers 라는 컬렉션(일종의 테이블)

// 가져오기. 만약 없으면 새로 생성.

var customers = testdb.GetCollection<Customer>("Customers");

   

// INSERT - 컬렉션 객체의 Insert() 메서드 호출

// Insert시 _id 라는 자동으로 ObjectID 생성

// 이 _id는 해당 다큐먼트는 나타는 키.

Customer cust1 = new Customer { Name = "Kim", Age = 30 };

customers.Insert(cust1);

ObjectId id = cust1.Id;

   

// SELECT - id로 검색

IMongoQuery query = Query.EQ("_id", id);

var result = customers.Find(query).SingleOrDefault();

if (result != null)

{

   Console.WriteLine(result.ToString());

}

   

// UPDATE

//    Save() = 전체 다큐먼트 갱신.

//    Update() = 부분 수정

cust1.Age = 31;

customers.Save(cust1);           

   

// DELETE

var qry = Query.EQ("_id", id);

customers.Remove(qry);

 

 

예제 FindAndModify

 

static Tuple<Int64, Int64> StoreUniqueNumber(int Count)

{

    MongoClient cli = new MongoClient(DB_ConnectString);

    MongoDatabase db = cli.GetServer().GetDatabase(BasicLogDatabaseName);

    var UniqueNumberCol = db.GetCollection<BsonDocument>("UniqueNumber");

   

    bool IsLoop = true;

   

    while (IsLoop)

    {

        var result = UniqueNumberCol.FindAll().SingleOrDefault();

   

        var firstNum = result["firts"].ToInt64();

        var lastNum = result["last"].ToInt64();

   

        var query = Query.And(

            Query.EQ("firts", firstNum),

            Query.EQ("last", lastNum)

        );

   

        var update = Update.Set("firts", lastNum + 1).Set("last", lastNum + Count);

   

        var newResult = UniqueNumberCol.FindAndModify(query, SortBy.Null, update, true);

           

        if (newResult.Ok)

        {

            var newFirstNum = result["firts"].ToInt64();

            var newLastNum = result["last"].ToInt64();

   

            return Tuple.Create(newFirstNum, newLastNum);

        }

    }

   

    return Tuple.Create((Int64)0, (Int64)0);

}

 

 

특정 필드 제외, 특정 필드만 쿼리하기

  • 특정 필드 제외
     

    MongoClient cli = new MongoClient(DB_ConnectString);

    MongoDatabase db = cli.GetServer().GetDatabase(BasicLogDatabaseName);

    var UniqueNumberCol = db.GetCollection<BsonDocument>("UniqueNumber");

       

    // _id 필드만 제외하고 모든 필드 데이터를 가져온다

    var newResult = UniqueNumberCol.FindAll().SetFields(Fields.Exclude("_id"));

  • 특정 필드만 가져오기
     

    MongoClient cli = new MongoClient(DB_ConnectString);

    MongoDatabase db = cli.GetServer().GetDatabase(BasicLogDatabaseName);

    var UniqueNumberCol = db.GetCollection<BsonDocument>("UniqueNumber");

       

    // money, level 필드 데이터만 가져온다

    var newResult = UniqueNumberCol.FindAll().SetFields(Fields.include("money", "level"));

     

 

날짜 쿼리

  • 특정날짜의 데이터 개수 알아내기
     

    // 어제 날짜

    dateTime = DateTime.Now.AddDays(-1);

    // 0시로 만들기 위해서

    DateTime dateTime2 = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day);

    var count = DBWork.DBDataMining.DailyNewUserStatistics(db, dateTime2);

       

    static public long DailyNewUserStatistics(MongoDBLib dbLib, DateTime dateTime)

    {

        var collection = dbLib.BasicLogDB.GetCollection<BsonDocument>("NewUser");

       

            //

        var query = Query.And(Query.GTE("date", dateTime.ToUniversalTime()), Query.LTE("date", dateTime.AddDays(1).ToUniversalTime()));

        var count = collection.Find(query).Count();

        return count;

    }

     

 

중복 제외

 

/*

{

    "_id" : ObjectId("5209d0507dbe2af068a42aec"),

    "ID" : "jacking75",

    "Uniq" : 5,

    "date" : ISODate("2013-08-12T06:21:04Z")

}

*/

   

DateTime datetime = MongoDBLib.StringToDateTime(yyyyMMddHHmm);

   

// 로그인한 총 수를 얻는다

var collection = dbLib.BasicLogDB.GetCollection<BsonDocument>("LoginUser");

var query = Query.And(Query.GTE("date", datetime), Query.LTE("date", datetime.AddDays(1)));

   

// ID 필드 값 중 중복된 것을 제외하고 개수를 구한다

var UniqueLoginUserCount = collection.Distinct("ID", query).Count();

 

 

 

LINQ

기본

  • 필요한 네임스페이스

MongoDB.Driver

MongoDB.Driver.Builders

MongoDB.Driver.Linq

MongoDB.Bson

MongoDB.Bson.Serialization.Attributes

 

 

[BsonIgnoreExtraElements]

public class AddressEntry

{

  [BsonId]

  public BsonObjectId _id { get; set;}

  public string Name { get; set; }

  public DateTime Birthday { get; set; }

  public List<Email> EmailAddrs { get; set; }

   

  [BsonIgnore]

   public string Detail { get; set; }  // 맵핑하지 않는다

}

   

[BsonIgnoreExtraElements]

public class Email

{

  public string DisplayName { get; set; }

  public string MailAddress { get; set; }

}

   

   

// MongoDB에 접속

MongoClient cli = new MongoClient();

// Database를 선택

MongoDatabase db = cli.GetServer().GetDatabase("TestDB");

// 컬렉션 취득

MongoCollection<AddressEntry> col = db.GetCollection<AddressEntry>("AddressBook");

 

public void Order_Where_Member_1()

{

    var orderCollection = GetCollection(); // 컬렉션 취득을 함수화

   

    var orders = orderCollection.AsQueryable().Where( x => x.MemberId == 1 ).ToList();

   

    orders.ForEach( x =>

            {

                WriteOrder( x );

                x.OrderDetails.ToList().ForEach( y => WriteOrderDetail( y ) );

            }

        );

}

 

 

&&

 

var query = from e in collection.AsQueryable<Employee>()

      where

         e.EmployeeStatus == Status.Active &&

         e.Salary > 100000

      select e;

   

// translates to:

{ EmployeeStatus : 1, Salary : { $gt : 100000 } }

 

 

문자열에서 일부 문자 찾기

 

var query = from e in collection.AsQueryable<Employee>()

      where e.Name.Contains("oh")

      select e;

   

// translates to:

{ nm: /oh/s }

   

   

var query = from e in collection.AsQueryable<Employee>()

      where e.Name.StartsWith("John")

      select e;

   

// translates to:

{ nm: /^John/s }

 

 

string Length, IsNullOrEmpty

 

var query = from e in collection.AsQueryable<Employee>()

      where e.Name.Length == 4

      select e;

   

// translates to:

{ nm: /^.{4}$/s }

   

   

var query = from e in collection.AsQueryable<Employee>()

      where string.IsNullOrEmpty(e.Name)

      select e;

   

// translates to:

{ $or : [ { nm: { $type : 10 } }, { nm: "" } ] }

 

 

string ToLower

 

var query = from e in collection.AsQueryable<Employee>()

      where e.Name.ToLower() == "john macadam"

      select e;

   

// translates to:

{ nm: /^john macadam$/is }

 

 

array element, Length

 

var query = from e in collection.AsQueryable<Employee>()

      where e.Skills[0] == "Java"

      select e;

   

// translates to:

{ "Skills.0" : "Java" }

   

   

var query = from e in collection.AsQueryable<Employee>()

       where e.Skills.Length == 3

       select e;

   

// translates to:

{ Skills : { $size : 3 } }

 

 

dotted names

 

var query = from e in collection.AsQueryable<Employee>()

      where e.Address.City == "Hoboken"

      select e;

   

// translates to:

{ "Address.City" : "Hoboken" }

 

 

$in

 

var states = new [] { "NJ", "NY", "PA" };

var query = from e in collection.AsQueryable<Employee>()

      where states.Contains(e.Address.State)

      select e;

   

// translates to:

{ "Address.State" : { $in : [ "NJ", "NY", "PA" ] } }

   

   

// alternative syntax using C#/.NET driver "In" method

var query = from e in collection.AsQueryable<Employee>()

     where e.Address.State.In(states)

     select e;

 

 

$in/$all with arrays

 

var desiredSkills = new [] { "Java", "C#" };

var query = from e in collection.AsQueryable<Employee>()

      where e.Skills.ContainsAny(desiredSkills)

      select e;

   

// translates to:

{ "Skills" : { $in : [ "Java", "C#" ] } }

   

   

var query = from e in collection.AsQueryable<Employee>()

     where e.Skills.ContainsAll(desiredSkills)

     select e;

   

// translates to:

{ "Skills" : { $all : [ "Java", "C#" ] } }

// note: ContainsAny and ContainsAll are defined by the C#/.NET

driver and are not part of standard LINQ

 

 

$elemMatch

 

var query = from e in collection.AsQueryable<Employee>()

   where

      e.Addresses.Any(a =>

         a.City == "Hoboken" &&

         a.State == "NJ")

   select e;

   

// translates to:

{ "Addresses" : { $elemMatch :

   { City : "Hoboken", State : "NJ" } } }

 

 

Mixing LINQ with MongoDB queries

 

var query = from e in collection.AsQueryable()

      where

         e.Salary > 50000 &&

         Query.NotExists("EmployeeStatus").Inject()

      select e;

   

// translates to:

{

   Salary : { $gt : 50000 },

   EmployeeStatus : { $exists : false }

}

 

 

 

참고 문서

  • What's new in the .NET Driver

  • CSharp Driver LINQ Tutorial

 

 

Error Code

'DataBase' 카테고리의 다른 글

SQL 소스 이력 관리  (0) 2013.04.11
SQL Server 설치 후 꼭 해줘야할 12가지 작업 DB_BI  (0) 2012.09.28
SQL Injection (SQL 인젝션)에 대한 보안  (0) 2012.09.28
MS SQL 시작 명령어  (0) 2011.08.29
MS SQL 명령어 모음  (0) 2011.08.29
Posted by 퓨전마법사
,