【问题标题】:Remove in MongoDb chsarp fails when using the _id使用 _id 时,在 MongoDb chsarp 中删除失败
【发布时间】:2013-12-31 20:44:37
【问题描述】:

在示例程序中,当我想使用 id 时,从 mongo db 中删除项目不起作用。 我假设问题是我的班级有一个 Id 属性,但 mongo 使用 _id ?

因此,当我在以下代码中触发删除时,没有任何变化。将 remove 与使用名称或值的查询一起使用,一切都按预期工作,并且项目被删除。

有什么提示吗?

MongoServer server = MongoServer.Create(@"mongodb://localhost/?safe=true");
server.Connect();
var db = server.GetDatabase("data");
var collection = db.GetCollection<Foo>("foo");

string id = Guid.NewGuid().ToString();
Foo a = new Foo();
a.Id = id;
a.name = "Boas";
a.Value = 1;

collection.Insert<Foo>(a);
Console.WriteLine(collection.Count()+ " items"); // Count is 1
collection.Remove(Query.EQ("_id",id));
Console.WriteLine(collection.Count() + " items"); // Count is still 1 :-( should be 0
Console.ReadLine();

补充: 当我对 Find() 使用相同的查询时,会找到该项目。所以我不明白为什么 find 确实找到了元素并且 remove 没有删除它。

collection.Find(Query.EQ("_id",id)).Count() // returns 1 element

【问题讨论】:

    标签: mongodb mongodb-.net-driver


    【解决方案1】:

    我一遍又一遍地这样做,它不断地打印出 1 个项目,然后是 0 个项目。您确定您的收藏中还没有项目吗?

    在您的 collection.Insert(a) 之后,添加一个 collection.RemoveAll()。

    【讨论】:

    • 嗯,我擦除了整个数据库并重新创建了一个新数据库。现在它可以工作了。有点奇怪。谢谢你的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多