Mongodb中数据聚合之MapReduce
Mongodb是针对大数据量环境下诞生的用于保存大数据量的非关系型数据库,针对大量的数据,如何进行统计操作至关重要,那么如何从Mongodb中统计一些数据呢? 在Mongodb中,给我们提供了三种用于数据聚合的方式: (1)简单的用户聚合函数; (2)使用aggregate
Mongodb是针对大数据量环境下诞生的用于保存大数据量的非关系型数据库,针对大量的数据,如何进行统计操作至关重要,那么如何从Mongodb中统计一些数据呢?
在Mongodb中,给我们提供了三种用于数据聚合的方式:
(1)简单的用户聚合函数;
(2)使用aggregate进行统计;
(3)使用mapReduce进行统计;
今天我们首先来讲讲mapReduce是如何统计,在后续的文章中,将另起文章进行相关说明。
MapReduce是啥呢?以我的理解,其实就是对集合中的各个满足条件的文档进行预处理,整理出想要的数据然后进行统计得到最终的统计结果。其中map函数用于对集合中的各个满足条件的文档进行预处理,整理出想要的数据。Reduce函数用于对整理出的数据进行处理得到统计结果。Map函数和Reduce函数都是JavaScript函数。
首先,我们先构造一个测试数据集test,使用js脚本往集合中随机插入一组数据,每条记录是哪个人花了多少钱买了什么东西。具体脚本test1.js如下:
<span style="font-size:18px;">for( var i=0; i=3 && rID=5 && rID</span>
接下来我们通过在控制台执行脚本来向数据库插入具体的数据,具体执行指令如下:
<span style="font-size:18px;">mongo 127.0.0.1:27017/test J:/test1.js</span>
执行之后,通过MongoVUE来查看下具体的数据,如下所示,数据已经插入到集合中了:
接下来,我们可以做几个简单的统计操作了。
(1)统计不同用户都买了多少个商品?编写js脚本test2.js,将结果保存到statis1集合中。
<span style="font-size:18px;"><span style="font-size:18px;">map=function(){ emit(this.user,1); } reduce=function(key, values){ var count = 0; values.forEach(function(val){count += val}); return count; } db.test.mapReduce(map, reduce, {out:"statics1"});</span></span>
按照刚才执行脚本的方式执行test2.js,并查看数据:

从数据库就可以直观看到统计数据了,若想查看某个人如majing购买了多少个商品,直接使用
<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;">db.statics1.find({"_id":"majing"});</span></span></span>
脚本test3.js如下所示:
<span style="font-size:18px;"><span style="font-size:18px;">map=function(){ emit({user:this.user,sku:this.sku},1); } reduce=function(key, values){ var count = 0; values.forEach(function(val){count += val}); return count; } db.test.mapReduce(map, reduce, {out:"statics2"});</span></span>
总共返回了10条记录。此时如果我们想查找某个用户购买商品的情况,可以使用下面的查询方法:
<span style="font-size:18px;"><span style="font-size:18px;">db.statics2.find({"_id.user":"majing"});</span></span>

如果我们想查找某个用户购买某个商品的情况,可以使用下面的查询方法:
(3)统计每个用户购买商品的总量及花费的总金额
脚本test4.js如下所示:
<span style="font-size:18px;"><span style="font-size:18px;">map=function(){ emit({user:this.user},{totalprice:this.price,count:1}); } reduce=function(key, values){ var res = {totalprice:0.00,count:1}; values.forEach(function(val){res.totalprice += val.totalprice;res.count+=val.count;}); return res; } db.test.mapReduce(map, reduce, {out:"statics3"});</span></span>
按照刚才执行脚本的方式执行test4.js,并查看数据:

(4)统计每个用户购买商品的平均价钱
在这个情景下,我们需要用到说道mapReduce里的另一个参数finalize,该参数是一个javascript脚本函数,用于对reduce后的集合进行一个后期处理操作。
执行脚本test5.js,具体如下所示:
<span style="font-size:18px;"><span style="font-size:18px;">map=function(){ emit({user:this.user},{totalprice:this.price,count:1}); } reduce=function(key, values){ var res = {totalprice:0.00,count:1,average:0}; values.forEach(function(val){res.totalprice += val.totalprice;res.count+=val.count;}); return res; } finalizeFunc=function(key,reduceResult){ reduceResult.totalprice=(reduceResult.totalprice).toFixed(2); reduceResult.average=(reduceResult.totalprice/reduceResult.count).toFixed(2); return reduceResult; } db.test.mapReduce(map, reduce, {out:"statics4",finalize:finalizeFunc});</span></span>
执行之后查看得到的数据,具体如下所示,显示了总价钱,商品数量和商品单价。
如果想查找某个人的,可以和上面的查询方法一样,使用find()方法进行查询:
<span style="font-size:18px;"><span style="font-size:18px;">db.statics4.find({"_id.user":"majing"});</span></span>
以上通过4个简单的例子对Mongodb中的MapReduce进行了简单的说明,当然MapReduce功能很强大,大家如果想知道其他高级的使用方法,可以到Mongodb的官网进行查阅和学习,网址为 https://docs.mongodb.com/manual/reference/method/db.collection.mapReduce/ ,谢谢。

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

AI Hentai Generator
Generate AI Hentai for free.

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

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

It is recommended to use the latest version of MongoDB (currently 5.0) as it provides the latest features and improvements. When selecting a version, you need to consider functional requirements, compatibility, stability, and community support. For example, the latest version has features such as transactions and aggregation pipeline optimization. Make sure the version is compatible with the application. For production environments, choose the long-term support version. The latest version has more active community support.

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

New SOTA for multimodal document understanding capabilities! Alibaba's mPLUG team released the latest open source work mPLUG-DocOwl1.5, which proposed a series of solutions to address the four major challenges of high-resolution image text recognition, general document structure understanding, instruction following, and introduction of external knowledge. Without further ado, let’s look at the effects first. One-click recognition and conversion of charts with complex structures into Markdown format: Charts of different styles are available: More detailed text recognition and positioning can also be easily handled: Detailed explanations of document understanding can also be given: You know, "Document Understanding" is currently An important scenario for the implementation of large language models. There are many products on the market to assist document reading. Some of them mainly use OCR systems for text recognition and cooperate with LLM for text processing.
