1

Since a few people have been misled because I only mentioned MongoDB in the title: the question is about how to do this in MongoDB, on a property.

I have an an object like this:

{
    List<string> MyQueue;
}

Is there a way to clamp the number of entries to a specific number so that when I push new values in, older values may get dropped?

Thomas
  • 10,933
  • 14
  • 65
  • 136
  • 1
    Possible duplicate of [Fixed size queue which automatically dequeues old values upon new enques](https://stackoverflow.com/questions/5852863/fixed-size-queue-which-automatically-dequeues-old-values-upon-new-enques) – Ousmane D. Dec 25 '17 at 15:35
  • I don't agree with the "Possible duplicate", how is this related to MongoDB? – thmshd Dec 25 '17 at 15:37
  • Have you checked out "capped collections" in general? It's not quite working for a Property like this, but it will work for a collection. https://stackoverflow.com/a/30969330/265165 – thmshd Dec 25 '17 at 15:40
  • Aominè, your link is not mongodb related; the key is to see if the DB can handle it.. not how to do it in C# :) – Thomas Dec 25 '17 at 15:44
  • thmshd: yes, I had a look, but it is about the whole collection, for example if you want to keep a log and remove the old entries; what I'm trying to do is the same idea, but only on a property – Thomas Dec 25 '17 at 15:45

1 Answers1

0

You could create a custom generic queue like this:

public class FixedQueue<T>
{
    private ConcurrentQueue<T> m_Queue = new ConcurrentQueue<T>();
    private Int3 m_Limit;
    private Object m_Lock = new Object();

    public Int32 Limit
    {
        get { return m_Limit; }
        set { m_Limit = value; }
    }

    public FixedQueue<T>(Int32 limit)
    {
        m_Limit = limit;
    }

    public void Enqueue(T obj)
    {
        m_Queue.Enqueue(obj);

        lock (m_Lock)
        {
            T overflow;
            while ((m_Queue.Count > m_Limit) && m_Queue.TryDequeue(out overflow)) ;
        }
    }
}

Upon enqueuing new items, it will automatically dequeue all the oldest items that overflow the set limit.

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98