[英]C# and MongoDB Delete Records Using List Of ObjectId's
I need to delete some records from a collection in mongo db using official C# driver. 我需要使用官方C#驱动程序从mongo db中的集合中删除一些记录。 My code is as follows. 我的代码如下。
public static void Remove(List<ObjectId> objectIds)
{
ObjectMongoCollection.Remove(Query.In("NotificationId", new BsonArray(objectIds)), SafeMode.True);
}
public class Notification
{
public static MongoCollection<Notification> ObjectMongoCollection = MongoHelper.GetMongoServer("MongoKelimeYarisi").GetDatabase("KelimeYarisi").GetCollection<Notification>("Notification");
[BsonId]
public ObjectId NotificationId { get; set; }
public int PlayerId { get; set; }
public string OpponentName { get; set; }
public string gameId { get; set; }
public DateTime CreateDate { get; set; }
public NotificationStatus Status = NotificationStatus.New;
public NotificationType Type = NotificationType.RoundSubmit;
public bool IsPushed { get; set; }
It runs without an error but doesn't seem to work. 它运行没有错误,但似乎不起作用。 How can i delete records using a list of ObjectIds. 如何使用ObjectIds列表删除记录。
Also tried: 还尝试过:
ObjectMongoCollection.Remove(Query.In("_id", new BsonArray(objectIds)), SafeMode.True);
I used a different approach to obtain a mongo query and that worked. 我使用不同的方法来获取mongo查询并且有效。 I built a linq query and converted it to a mongo query. 我构建了一个linq查询并将其转换为mongo查询。
public static void Remove(List<ObjectId> objectIds)
{
var linqQuery = from n in ObjectMongoCollection.AsQueryable<Notification>() where n.NotificationId.In(objectIds) select n;
var mongoQuery = ((MongoQueryable<Notification>)linqQuery).GetMongoQuery();
ObjectMongoCollection.Remove(mongoQuery);
}
I am unable to reproduce this. 我无法重现这一点。 I wrote a test program as similar as possible to your code and it does in fact Remove the multiple records. 我编写了一个尽可能与您的代码类似的测试程序,它确实删除了多个记录。 Here's my test program: 这是我的测试程序:
http://pastie.org/4618039 http://pastie.org/4618039
Let me know if you have any further questions. 如果您有任何其他问题,请与我们联系。
You could write a method called something like: 您可以编写一个名为的方法:
public void destroy() {
...
}
In this method you will use the list of your ObjectIds and loop through them. 在此方法中,您将使用ObjectIds列表并循环遍历它们。
foreach(Enitity enitity in entities) {
...
}
Than you can use MongoDB.Driver.Linq to execute specific queries in your list: 您可以使用MongoDB.Driver.Linq在列表中执行特定查询:
var query = Query<Entity>.EQ(e => e.Attribute, entity.Value);
db.GetCollection<Entity>("Entity").Remove(query);
Where Value would be the object's value that you want. 其中Value是您想要的对象的值。 This will remove the elements from the db that contains specific value. 这将从包含特定值的db中删除元素。
I hope you find this useful. 希望这个对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.