How do you count the amount of documents in a MongoDB collection within Node?

时间:2015-11-12 10:54:00

标签: node.js mongodb

Quite an odd situation, I've tried numerous solutions and I can't seem to crack it.

A lot of the resources I've found only include mongo console commands, I'm not sure how you'd write this in Node.js.

The reason I'm trying to work this out is I'm trying to make each documents 'id' iterate from the last, so the attempt is to find the amount of documents in a collection, add one and then use that number as the 'id' for the new document.

1 个答案:

答案 0 :(得分:5)

要获取集合中的文档数量,请使用db.collection.find({}).count()

但是,你要做的事情是行不通的。当您对数据库进行大量并行访问时,多个线程可能同时执行此操作,接收相同的计数,从而插入具有相同ID的文档。根据{{​​3}},像MongoDB这样的分布式数据库无法提供这种一致性。

您应该做的是依靠MongoDB CAP theorem作为文档的唯一标识符。当您没有为_id提供自己的值时,MongoDB会自动为每个文档生成这些内容。 ObjectId是全球唯一的(足够用于任何实际目的),因此您不会遇到任何冲突。它们也以时间戳开头,因此当您按_id订购时,您会得到一个大致按时间顺序的顺序(如前所述,分布式系统无法提供严格的时间顺序)。 / p>

根据经验,无论何时在SQL中使用AUTO_INCREMENT,都可能在MongodDB中使用ObjectId。