简体   繁体   English

使用C#在mongodb中按ID字段删除文档

[英]Remove document by id field in mongodb using C#

I am trying to delete the document by id, which is of type ObjectId, I do have converted the string to ObjectId and passed as parameter to remove from collection, but I am not able to delete the record. 我正在尝试通过ID(类型为ObjectId)删除文档,我确实已将字符串转换为ObjectId,并已将其作为要从集合中删除的参数传递,但是我无法删除记录。

I don't know what is the actuall reason behind, Looking for solution, below is my code sample: 我不知道背后的实际原因是“寻找解决方案”,这是我的代码示例:

 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)
            {

            }
        }

Try below code, and see whether is working? 尝试下面的代码,看看是否有效?

var query = Query.EQ("_id", new BsonObjectId("objectID"));

Or 要么

var query = Query.EQ("_id", name);
records.Remove(query);

Finally, This worked for me, without converting the string to object id and pass as a parameter as a string itself. 最后,这对我有用,无需将字符串转换为对象id并作为字符串本身作为参数传递。

var query = Query.EQ("_id", objectID);
records.Remove(query);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM