限制插入mongodb [英] Limit inserts in mongodb

查看:93
本文介绍了限制插入mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表格中输入以下文件:

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

现在,我的应用程序要求RoomUsers中的每个房间中只能有数量有限的用户.假设每个房间最多只能有5位用户. 该如何解决?

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?

如果我使用的是RDBM,也许可以采用这种策略(我不确定它是否是最好的策略,但仍然如此):

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确实没有事务.如何在noSql中完成同一件事?

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

推荐答案

有一种方法可以让您自动完成.

There is one approach will let you do it atomically.

您应该将userIds嵌入到RoomUsers集合中.像

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

这篇关于限制插入mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆