Mongodb中随机的查询文档记录
在实际应用场景中,几乎都会有随机获取数据记录的需求。而这个需求在 Mongodb 却不是很好实现,就目前而言,大致上有三种解决方案: 先计算出一个从 0 到记录总数之间的随机数,然后采用 skip(yourRandomNumber) 方法。 为每一条记录增设 random 字段,插入
在实际应用场景中,几乎都会有随机获取数据记录的需求。而这个需求在 Mongodb 却不是很好实现,就目前而言,大致上有三种解决方案:
- 先计算出一个从
0
到记录总数之间的随机数,然后采用skip(yourRandomNumber)
方法。 - 为每一条记录增设
random
字段,插入数据时赋值为Math.random()
,查询时采用$gte
和$lte
。 - 借助 Mongodb 对地理空间索引(
geospatial indexes
)的支持,从而可以在第二种方法的基础上来实现随机记录的获取。
因为 Mongodb 是不建议使用skip
方法的,所以这里就略去第一种方法吧。
方法二
> db.twitter.save({ username: 'heroic', random: Math.random(), content: 'balabala0...' }) > db.twitter.save({ username: 'heroic', random: Math.random(), content: 'balabala1...' }) > db.twitter.save({ username: 'heroic', random: Math.random(), content: 'balabala2...' }) > db.twitter.save({ username: 'heroic', random: Math.random(), content: 'balabala3...' }) > db.twitter.save({ username: 'heroic', random: Math.random(), content: 'balabala4...' }) /* more records... */ /* create index */ > db.twitter.ensureIndex({ username: 1, random: 1 }) > rand = Math.random() > result = db.twitter.findOne({ username: 'heroic', random: { $gte: rand } }) > if (result == null) { > result = db.twitter.findOne({ username: 'heroic', random: { $lte: rand } }) > }
方法三
> db.twitter.save({ username: 'heroic', random: [Math.random(), 0], content: 'balabala0...' }) > db.twitter.save({ username: 'heroic', random: [Math.random(), 0], content: 'balabala1...' }) > db.twitter.save({ username: 'heroic', random: [Math.random(), 0], content: 'balabala2...' }) > db.twitter.save({ username: 'heroic', random: [Math.random(), 0], content: 'balabala3...' }) > db.twitter.save({ username: 'heroic', random: [Math.random(), 0], content: 'balabala4...' }) /* more records... */ /* create index */ > db.twitter.ensureIndex({ username: 1, random: '2d' }) > result = db.twitter.findOne({ username: 'heroic', random: { $near: [Math.random(), 0] } })
更多关于 Mongodb 地理空间索引资料,请参见这里。
目前这几种方案似乎都不是很理想,但是也没有其他办法了,所以广大程序员们就相约到 Mongodb 的官方 jira 提了相应的需求,但是目前仍然没有任何的响应。可以参见这里,围观一下。
原文地址:Mongodb中随机的查询文档记录, 感谢原作者分享。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Yesterday during the interview, I was asked whether I had done any long-tail related questions, so I thought I would give a brief summary. The long-tail problem of autonomous driving refers to edge cases in autonomous vehicles, that is, possible scenarios with a low probability of occurrence. The perceived long-tail problem is one of the main reasons currently limiting the operational design domain of single-vehicle intelligent autonomous vehicles. The underlying architecture and most technical issues of autonomous driving have been solved, and the remaining 5% of long-tail problems have gradually become the key to restricting the development of autonomous driving. These problems include a variety of fragmented scenarios, extreme situations, and unpredictable human behavior. The "long tail" of edge scenarios in autonomous driving refers to edge cases in autonomous vehicles (AVs). Edge cases are possible scenarios with a low probability of occurrence. these rare events

How to use Go framework documentation? Determine the document type: official website, GitHub repository, third-party resource. Understand the documentation structure: getting started, in-depth tutorials, reference manuals. Locate the information as needed: Use the organizational structure or the search function. Understand terms and concepts: Read carefully and understand new terms and concepts. Practical case: Use Beego to create a simple web server. Other Go framework documentation: Gin, Echo, Buffalo, Fiber.

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

Apps not loading on your iPhone? If an app takes a long time to load, that's not normal. With the exception of apps that are still in beta, they should load instantly when you open them on your iPhone. Except for some heavy games, if all the apps on your phone are loading slowly or not loading at all, you should follow the steps below to fix it. Fix 1 – Update App (if applicable) Haven’t updated your app in a while? Updating it to the latest version should resolve the issue. Step 1 – Open the AppStore. Step 2 – Just start typing the name of the app in the search box and open the app directly from the suggestions. Step 3 – Click to go to Special

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Guest | Interview by Xu Xiaoqiang | Written by Zhang Xiaonan | Produced by Li Meihan | 51CTO Technology Stack (WeChat ID: blog51cto) Since the popularity of generative AI, AI seems to have "struggled" with the role of programmers. Almost every once in a while, the topic of whether AI programming tools can replace programmers will be discussed again. The heated discussion aroused by AI programming makes people confused: Will this set off a productivity revolution in the field of programming? Or is this another over-hyped stunt? Thanks to AI programming, Baidu has achieved a 10% improvement in human efficiency, and 27% of the new code submitted by engineers today was generated by AI. The pioneers of this answer are the major manufacturers who are exploring this answer. However, as the architect of Baidu Comate, I am also the founder of this product.

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies
