2012-08-30 56 views
4

我需要使用官方C#驅動程序從mongo db中的集合中刪除一些記錄。我的代碼如下。C#和MongoDB使用ObjectId列表刪除記錄

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; } 

它運行沒有錯誤,但似乎沒有工作。我如何使用ObjectId列表刪除記錄。

也試過:

ObjectMongoCollection.Remove(Query.In("_id", new BsonArray(objectIds)), SafeMode.True); 

回答

4

我無法重現此。我寫了一個儘可能類似於你的代碼的測試程序,它實際上刪除了多個記錄。這裏是我的測試程序:

http://pastie.org/4618039

讓我知道,如果您有任何進一步的問題。

+0

想要添加:如果使用無類型的查詢構建器,則確實使用「_id」作爲字段名稱。我添加了一段註釋的代碼行,說明如何使用類型化查詢構建器創建相同的查詢,這通常是首選的方法。 –

5

我用一種不同的方法來獲得一個mongo查詢並且工作。我構建了一個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); 
    } 
1

你可以寫一個方法調用,像這樣:

public void destroy() { 
     ... 
    } 

在這種方法中,你將通過他們使用你的ObjectID的列表和循環。

foreach(Enitity enitity in entities) { 
    ... 
} 

比你可以使用MongoDB.Driver.Linq要在列表中執行特定的查詢:

var query = Query<Entity>.EQ(e => e.Attribute, entity.Value); 
db.GetCollection<Entity>("Entity").Remove(query); 

其中value是您想要的對象的值。 這將刪除包含特定值的數據庫中的元素。

我希望你覺得這個很有用。

+0

由於您在循環中不使用mongo驅動程序進行查詢,似乎看起來效率低下? – Imdad