C# MongoDB MongoDB Driver를 구식 버전에서 업그레이드 함에 따라 변경된 문법을 정리.

 

 

MongoClient

// Old
MongoClient client = new MongoClient("CONNECTION_STRING");
// New: Same syntax.
MongoClient client = new MongoClient("CONNECTION_STRING");

 

 

MongoServer

//Old
MongoServer server = client.GetServer();
//New: MondoServer is deprecated.

 

 

MongoDatabase

// Old
MongoDatabase db = server.GetDatabase("DATABASE_NAME");
// New
IMongoDatabase db = client.GetDatabase("DATABASE_NAME");

 

 

Run Ping

// Old
db.RunCommand("ping");
// New
db.RunCommand<BsonDocument>("{'ping': 1}");

 

 

MongoCollection

// Old
MongoCollection mongoCollection = mongoDatabase.GetCollection<YourDocumentClass>("COLLECTION NAME");
// New
IMongoCollection<YourDocumentClass> mongoCollection = mongoDatabase.GetCollection<YourDocumentClass>("COLLECTION NAME");

 

 

Check the collection is exists

// Old
mongoCollection.Exists();
// New
if(mongoCollection != null)  {}

 

 

Check the index is exists

// Old
mongoCollection.IndexExistsByName(collectionIndex);
// New
listIndexes.SelectMany(idx => idx.Elements).Where(elem => elem.Name.Contains("name")).Select(name => name.Value.ToString()).Contains("INDEX_NAME");

 

 

Create a new index

// Old
IndexKeysBuilder<YourDocumentClass> keys = IndexKeys<YourDocumentClass>.Ascending(x => x.f1).Descending(x => x.f2);
IndexOptionsBuilder options = IndexOptions.SetName("INDEX_NAME");
mongoCollection.CreateIndex(keys, options);
// New
CreateIndexModel<YourDocumentClass> indexModel = new CreateIndexModel<YourDocumentClass>( 
    Builders<YourDocumentClass>.IndexKeys.Ascending(x => x.f1).Descending(x => x.f2),
    new CreateIndexOptions(){ Name: "INDEX_NAME"})
);
mongoCollection.Indexes.CreateOne(indexModel);

 

 

Find Query - FindOne

// Old
var findQuery = Query<YourDocumentClass>.EQ(x => x.f1, "VALUE");
YourDocumentClass doc = collection.FindOneAs<YourDocumentClass>(findQuery);
// New
var findQuery = Builders<YourDocumentClass>.Filter.Eq(x => x.f1, "VALUE");
List<YourDocumentClass> listYourDocumentClass = collection.Find(findQuery).Limit(1).ToList();
YourDocumentClass doc = listYourDocumentClass[0];

 

 

Update Query

// Old
var updateValues = Update<YourDocumentClass>.Set(x => x.f1, "VALUE");
WriteConcernResult result = collection.Update(findQuery, updateValues, UpdateFlags.Multi)
// New
var updateQuery = Builders<YourDocumentClass>.Update.Set(x => x.f1, "VALUE");
collection.UpdateMany(findQuery, updateQuery);

 

 

Delete Query

// Old
var query = Query<YourDocumentClass>.EQ(x => x.f1, "VALUE");
collection.Remove(query);
// New
var findQuery = Builders<YourDocumentClass>.Filter.Eq(x => x.f1, "VALUE");
collection.DeleteMany(findQuery);

 

 

Insert Query

// Old
collection.Insert(YourDocumentClass);
// New
collection.InsertOne(YourDocumentClass);

 

 

 

 

 

 

반응형

+ Recent posts