0

I'm working on creating an immutable append only event log for MongoDB, in this I need a sequence number genereated and can base it off of the count of documents, since there will be no removals from the event log. However, I'm trying to avoid having to do two operations on MongoDB and would rather it happen in one "transaction" within the database itself.

If I were to do this from the Mongo shell, it would be something like below:

db['event-log'].insertOne({SequenceNumber: db['event-log'].count() +1 })

Is this doable in any way with the regular API?

Prior to v4, there was the possibility of doing eval - which would have made this much easier.

Update

The reason for my need of a sequence number is to be able to guarantee the order in which they were inserted when reading them back. Default behavior of Mongo is to retrieve them in the $natural order and one can explicitly define that on .find() as well (read more here). Although documentation is clear on not relying on it, it seems that as long as there are no modifications / removal of documents already there, it should be fine from what I can gather.

I realized also that I might get around this in another way as well, I'm going to introduce an Actor framework and I could make my committer a stateful actor with the sequence number in it if I need it.

EinarI
  • 627
  • 1
  • 9
  • 14
  • 1
    I don't think it is possible by one query, check similar question [Auto increment in MongoDB to store sequence of Unique User ID](https://stackoverflow.com/questions/8384029/auto-increment-in-mongodb-to-store-sequence-of-unique-user-id) – turivishal Jul 04 '21 at 07:58
  • 1
    Note that your example in the shell is actually performing 2 separate operations to the database - first the count, and then using that result in the insert. – Joe Jul 04 '21 at 10:41
  • Thanks. You're right Joe, it is two operations - I was just hoping to do it at least in one go within the server without having to go back to the client. In cluster mode I can use session - making it transactional, which gives me the safety for concurrency I was hoping. But I might have come up with solution. I'll amend my question with a solution that I might be able to live with. – EinarI Jul 04 '21 at 16:38

0 Answers0