Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and MongoDB Delete Records Using List Of ObjectId's

Tags:

c#

mongodb

I need to delete some records from a collection in mongo db using official C# driver. 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.

Also tried:

ObjectMongoCollection.Remove(Query.In("_id", new BsonArray(objectIds)), SafeMode.True);
like image 266
hakan Avatar asked Dec 27 '22 18:12

hakan


2 Answers

I used a different approach to obtain a mongo query and that worked. I built a linq query and converted it to a mongo query.

    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);
    }
like image 141
hakan Avatar answered Dec 29 '22 09:12

hakan


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

Let me know if you have any further questions.

like image 21
Robert Stam Avatar answered Dec 29 '22 11:12

Robert Stam