1

I enter these documents in a table:

db.RoomUsers.insert( {userId: 1, roomId: 1} )
db.RoomUsers.insert( {userId: 2, roomId: 1} )
db.RoomUsers.insert( {userId: 3, roomId: 1} )
db.RoomUsers.insert( {userId: 4, roomId: 1} )

Now, my application requires that in RoomUsers there can be a limited number of user in each room. Let's say that there cannot be more than 5 user for each room. How to fix that?

If I was using an RDBM I could maybe have this strategy(Im not sure its the best one, but still):

1 - Count number of entries in RoomUsers where roomId = X
2 - If number of users is less than Y then:
2A - Start a transaction
2B - Insert new user in RoomUsers
2C - Count number of entries in RoomUsers where roomId = X
2D - If number of users is greater than Y then: Rollback. Otherwise: commit

MongoDB doesn't really have transaction, what I understand. How to accomplish the same thing in noSql?

oderfla
  • 1,695
  • 4
  • 24
  • 49

1 Answers1

2

There is one approach will let you do it atomically.

You should embed userIds into RoomUsers collection. Something like

{ "userIds" : [ 1, 2, 3, 4 ], "roomId" : 1 }

Now you can use the below update query.

db.RoomUsers.update( { roomId : 1, "userIds": { $not: {$size: 5 } } }, { $push : { "userIds":5 } } )

s7vr
  • 73,656
  • 11
  • 106
  • 127