skip to Main Content

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


  1. Chosen as BEST ANSWER

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

  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search