【问题标题】:Mongo DB update nested object using Mongo C# DriverMongodb 使用 Mongo C# Driver 更新嵌套对象
【发布时间】:2015-01-30 03:53:09
【问题描述】:

我对 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; }
}

这是我的上下文类

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”实体时,我应该怎么做。

【问题讨论】:

  • 你想更新什么?

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


【解决方案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);

【讨论】:

  • 我想通过嵌套在“ItemCategory”实体中的 Id 更新一个特定的“Item”实体,我应该怎么做
  • 放一个样本文件,你想要的结果在你的问题中
猜你喜欢
  • 2021-11-04
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
  • 2021-02-13
  • 2021-01-23
  • 1970-01-01
  • 2018-11-07
  • 2023-04-03
相关资源
最近更新 更多