2

I'm creating a match-making system via the MongoDB drivers for Golang.

I have a collection called sessions.

When a user tries to join a match, a find() query will return active sessions. Then the user will be placed in one of those active sessions.

But what if, at the same time, one of those sessions was closed via updateOne()? Then the documents from find() are no longer valid.

So I would like all queries in the collection to be blocked until updates are done.

I know I can implement my own mutex for this case. But I want to know if MongoDB has any API for this as well? If not, any examples to how I can approach this (whether it's with sync.Mutex or sync.RWMutex)?

haste
  • 99
  • 5
  • No. And it gets even worse for you if you have a replica set that allows reading from secondaries and/or several application servers. You should probably use `findAndModify` to do it in out step, and handle the case that the session was closed after the user joined it. – Rani Sharim Mar 26 '23 at 06:24
  • Possible duplicate: [How to wait while replicas are caught up master](https://stackoverflow.com/questions/68499266/how-to-wait-while-replicas-are-caught-up-master/68499823#68499823) – icza Mar 26 '23 at 06:35

1 Answers1

0

MongoDB is ACID compliant so it should be responsible for deciding what documents to return even when there's an insert in progress. If you do believe that your query isn't returning a document you wanted inserted then you need to solve the problem on the Go side.

Use channels to manange your control flow. Something along the lines of:

select {
case query := <-queryChan:
  // do mongo query, make sure to include a return channel in the query struct so you can collect your results
  query.results <- // the results
case insert := <-insertChan
  // do mongo insert
}

Wrap this in a single goroutine to ensure that your database operations happen in order.

Dan
  • 179
  • 1
  • 1
  • 13