我试图通过id删除文档,它是ObjectId类型,我确实已经将字符串转换为ObjectId并作为参数传递给从集合中删除,但是我无法删除记录。
我不知道背后的实际原因是什么,寻找解决方案,下面是我的代码示例:
public void DeleteRecords(string objectID)
{
try
{
// Create server settings to pass connection string, timeout, etc.
MongoServerSettings settings = new MongoServerSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
// Create server object to communicate with our server
MongoServer server = new MongoServer(settings);
MongoDatabase myDB = server.GetDatabase("DemoMongoDB");
MongoCollection<BsonDocument> records = myDB.GetCollection<BsonDocument>("Records");
//var query = Query<Records>.EQ(fd => fd._id, ObjectId.Parse(name));
var query = Query<Records>.EQ(e => e._id, new BsonObjectId(objectID));
records.Remove(query);
}
catch (Exception ex)
{
}
}
答案 0 :(得分:3)
尝试下面的代码,看看是否有效?
var query = Query.EQ("_id", new BsonObjectId("objectID"));
或
var query = Query.EQ("_id", name);
records.Remove(query);
答案 1 :(得分:0)
最后,这对我有用,没有将字符串转换为对象id并作为字符串本身作为参数传递。
var query = Query.EQ("_id", objectID);
records.Remove(query);