Mongodb使用Mongo C#Driver更新嵌套对象

时间:2015-01-30 03:53:10

标签: c# mongodb mongodb-.net-driver

我不太熟悉mongodb,我喜欢面向文档的数据库。我的应用程序有这些业务实体类:

public class ItemCategory
{
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    public string CategoryName { get; set; }
    public IList<Item> Items { get; set; }
}

public class Item
{
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    public string ItemName { get; set; }

    [BsonRepresentation(BsonType.Double)]
    public decimal UnitPrice { get; set; }
}

这是我的Context类

public class MongoDbContext
{
    private MongoDatabase database;

    public MongoDatabase Database
    {
        get { return database; }
        set { database = value; }
    }

    public MongoDbContext()
    {
        var client = new MongoClient(Settings.Default.constr);
        var server = client.GetServer();
        Database= server.GetDatabase(Settings.Default.db);            
    }

    public MongoCollection<ItemCategory> ItemCategories 
    { 
        get
        {
            return Database.GetCollection<ItemCategory>("itemcategories"); 
        }
    }
}

当我想通过嵌套在“ItemCategory”实体中的Id更新特定的“Item”实体时,我应该怎么做。

1 个答案:

答案 0 :(得分:-1)

  

首先,您应该通过Query课程找到目标文档,然后您必须使用Update课程来更新您的文档

在我的示例中,我将文档的CategoryName属性从"old name"更新为"new category name"

var collection = database.GetCollection<ItemCategory>("itemcategories");

var query = Query.And(Query<ItemCategory>.EQ(c => c.Id, "id"), Query<ItemCategory>.EQ(c => c.CategoryName, "old name"));
var update = Update<ItemCategory>.Set(c => c.CategoryName, "new category name");

collection.Update(query, update);