【问题标题】:MongoDB C# Remove doesn't workMongoDB C# 删除不起作用
【发布时间】:2012-09-22 03:44:48
【问题描述】:

我有此代码用于从 mongob 排序规则中删除项目

private MongoCollection<T> GetCollection()
    {
       connectionString = "mongodb://localhost/?safe=true";
       server = MongoServer.Create(connectionString);
       database = server.GetDatabase("CSCatalog"); 

        return database.GetCollection<T>("myCollectionName");
    }
public bool  Delete(T entity)
    {            
        var id = typeof(T).GetProperty("Id").GetValue(entity,null).ToString();            
        var query = Query.EQ("_id",id);
        var finded = GetCollection().Find(query); // return null
        var result= GetCollection().Remove(query, MongoDB.Driver.RemoveFlags.Single);  // no errors, but don't remove 

        return esito.Ok; //return true but donn't remove.


    }

GetCollection() 方法检索正确的集合,我已经对其宽度调试进行了测试。 在集合中有我要删除的项目,它与我在第一行检索到的 id 相同。

实体有一些字段和一个名为“Id”的 Objectid 字段

【问题讨论】:

  • 会发生什么? “不起作用”不够具体。

标签: mongodb collections mongodb-.net-driver mongodb-query


【解决方案1】:

如果.find() 从您的数据库中返回了某些内容,则您的finded 变量不应为null。它为 null 意味着您没有找到任何东西,因此不会删除任何内容。

这里发生的情况是,您在 _id 上查询 ObjectId,同时将该 ObjectId 作为 Id 存储在数据库中。

【讨论】:

    【解决方案2】:

    您创建的 _id 类型是 ObjectId 类,并且您试图将其等同于字符串,因此它无法删除。使用

    var queryId = new ObjectId(id);

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多