Delete document from MongoDB by _id range in c#

Viewed 38

My Mongo DB (using Azure Cosmos) reached max size of 20 GB. I didn't realize that, and now the app is not working. We were planning to delete old records (last 2 years). However, there is no date field in the document. I was thinking if _ts is maintained internally but looks like it is not. Then the only options is to use the _id (which is ObjectId). Can someone help on how to delete based on a date range using c#?

2 Answers

You can use getTimestamp method

In the shell, you can find creation date by this:

db.c.find()[0]["_id"].getTimestamp()

C# code will look similar to:

var client = new MongoClient();
var d = client.GetDatabase("d");
var c = d.GetCollection<BsonDocument>("c");
c.InsertOne(new BsonDocument());
var result = c.AsQueryable().First()["_id"].AsObjectId;
Console.WriteLine(result.CreationTime);

I managed to make it work using this:

            var startId = new ObjectId(startDateTime, 0, 0, 0);
            var endId = new ObjectId(endDateTime, 0, 0, 0);
            using (var cursor = await collection.Find(x => x["_id"] > startId && x["_id"] < endId).ToCursorAsync())
            {
                while (await cursor.MoveNextAsync())
                {
                    foreach (var doc in cursor.Current)
                    {
                        var creationTime = doc["_id"].AsObjectId.CreationTime;
                        var filter = Builders<BsonDocument>.Filter.Eq("_id", doc["_id"].AsObjectId);
                        try
                        {
                            var deleteResult = collection.DeleteMany(filter);                            
                        }
                        catch (Exception ex)
                        {
                            
                        }
                    }
                }
            }
Related