How to deserialize a BsonDocument object back to class

There are three ways actually: 1.Specify type you want to load directly in FindAs<> var docs = _collection.FindAs<MyType>(_document); 2.Deserialize document via BsonSerializer: BsonSerializer.Deserialize<MyType>(doc); 3.Map bson document manually to your class: var myClass = new Mytype(); myClass.Name = bsonDoc[“name”].AsString; For most cases you are okay with first approach. But sometimes, when your documents is unstructured, you … Read more

Get All ‘documents’ from MongoDB ‘collection’

Using the current version of the driver (v2.0) you can do that by passing a filter that matches everything: var documents = await SpeCollection.Find(_ => true).ToListAsync(); They have also added an empty filter (FilterDefinition.Empty) which will arrive in the next version of the driver (v2.1): var documents = await SpeCollection.Find(Builders<Project>.Filter.Empty).ToListAsync();

Upserting in Mongo DB using official C# driver

Version 2 of the MongoDB C# driver requires setting the IsUpsert flag in the write commands. This example will upsert an entire document. var newDoc = new BsonDocument { { “_id”, 123 }, { “someKey”, “someValue” } }; var result = await collection.ReplaceOneAsync( filter: new BsonDocument(“_id”, 123), options: new ReplaceOptions { IsUpsert = true }, … Read more

MongoDB and C#: Case insensitive search

The simplest and safest way to do that is using Linq: var names = namesCollection.AsQueryable().Where(name => name.FirstName.ToLower().Contains(“hamster”)); As explained in the tutorial ToLower, ToLowerInvariant, ToUpper and ToUpperInvariant all perform matches in a case insensitive way. After that you can use all the supported string methods like Contains or StartsWith. This example will generate: { “FirstName” … Read more

How to find min value in mongodb

You can use a combination of sort and limit to emulate min: > db.foo.insert({a: 1}) > db.foo.insert({a: 2}) > db.foo.insert({a: 3}) > db.foo.find().sort({a: 1}).limit(1) { “_id” : ObjectId(“4df8d4a5957c623adae2ab7e”), “a” : 1 } sort({a: 1}) is an ascending (minimum-first) sort on the a field, and we then only return the first document, which will be the … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)