你如何计算 Node 中 MongoDB 集合中的文档数量? [英] How do you count the amount of documents in a MongoDB collection within Node?

查看:83
本文介绍了你如何计算 Node 中 MongoDB 集合中的文档数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很奇怪的情况,我尝试了很多解决方案,但似乎无法破解.

我发现的很多资源仅包含 mongo 控制台命令,我不确定您会如何在 Node.js 中编写它.

我试图解决这个问题的原因是我试图让每个文档id"从最后一个迭代,所以尝试是找到集合中的文档数量,添加一个并然后使用该数字作为新文档的id".

解决方案

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

但是,您尝试执行的操作是行不通的.当您对数据库进行大量并行访问时,可能会有多个线程同时执行此操作,接收相同的计数,从而插入具有相同 ID 的文档.根据CAP定理,像MongoDB这样的分布式数据库无法提供这种一致性.>

你应该做的是依赖 MongoDB ObjectId 的 as文档的唯一标识符.当您没有为 _id 提供自己的值时,MongoDB 会自动为每个文档生成这些.ObjectId 是全局唯一的(对于任何实际目的来说都是唯一的),因此您不会遇到任何冲突.它们也以时间戳开头,因此当您按 _id 订购时,您会得到大致的时间顺序(如前所述,分布式系统不可能提供严格 时间顺序)).

根据经验,每当您在 SQL 中使用 AUTO_INCREMENT 时,您很可能会在 MongodDB 中使用 ObjectId.

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.

解决方案

To get the number of documents in a collection, use db.collection.find({}).count().

However, what you are trying to do will not work. When you have a lot of parallel accesses to the database, then it is possible that multiple threads do this at the same time, receive the same count and will thus insert a document with the same id. According to the CAP theorem, a distributed database like MongoDB can not provide this kind of consistency.

What you should do instead is rely on MongoDB ObjectId's as unique identifiers for documents. MongoDB generates these automatically for each document when you don't provide an own value for _id. ObjectId's are globally unique (unique enough for any practical purpose), so you won't get any collisions. They also begin with a timestamp, so when you order by _id you get a roughly chronological order (as previously stated, a strict chronological order is impossible to provide by a distributed system).

As a rule of thumb, whenever you would use AUTO_INCREMENT in SQL, you would likely use ObjectId's in MongodDB.

这篇关于你如何计算 Node 中 MongoDB 集合中的文档数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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