using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver.Builders;
using MongoDB.Bson;
using MongoDB.Driver;
namespace TestMongoPartialUpdate
{
public class TestObject
{
public int Id { get; set; }
public string Name { get; set; }
///
/// The problematic object, the key and value can be anything - all fail.
///
public Dictionary TestDictionary { get; set; }
}
class Program
{
private static MongoCollection m_Collection;
static void Main(string[] args)
{
var mongoServer = MongoServer.Create(new MongoConnectionStringBuilder { ConnectionString = "Server=localhost", SafeMode = SafeMode.True });
var mongoDatabase = mongoServer.GetDatabase("TestMongoPartialUpdate");
m_Collection = mongoDatabase.GetCollection(typeof(TestObject).Name);
Console.WriteLine("1. Inserting object");
var testObject = new TestObject { Id = 1, Name = "Test", TestDictionary = new Dictionary() };
m_Collection.Drop();
m_Collection.Insert(testObject);
Console.WriteLine("2. object was saved successfully, trying to fetch it");
var insertedTestObject = m_Collection.FindOneAs();
Console.WriteLine("3. Fetched object successfully, id: " + insertedTestObject.Id);
Console.WriteLine("4. Updating object");
testObject.TestDictionary.Add(Guid.NewGuid().ToString(), 1);
var updatedSuccessfully = UpdateObject(testObject.Id, "TestDictionary", testObject.TestDictionary);
try
{
if (updatedSuccessfully)
{
Console.WriteLine("5. object was updated successfully, trying to fetch it");
var updatedTestObject = m_Collection.FindOneAs();
// Not getting here!
Console.WriteLine("6. Fetched object successfully, the problem is gone! id: " + updatedTestObject.Id);
}
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine("Error when trying to fetch the updated object: " + ex.Message);
}
finally
{
Console.ReadLine();
}
}
private static bool UpdateObject(object id, string fieldName, object value)
{
var builder = new UpdateBuilder();
var type = value.GetType();
if (type.IsPrimitive || type.IsValueType || (type == typeof(string)))
{
builder.Set(fieldName, BsonValue.Create(value));
}
else
{
builder.Set(fieldName, value.ToBsonDocument());
}
var result = m_Collection.Update(Query.EQ("_id", BsonValue.Create(id)), builder, new MongoUpdateOptions { Flags = UpdateFlags.Multi });
return result.UpdatedExisting;
}
}
}