Okay so now I want to pick this up
and talk about the project operator. So a couple of
things to note about project, we can use project to
include fields from the original document. Remember that project works
with data in a single document at a time. And
we're essentially doing a shaping task with project. So the
simplest form of shaping, is simply specifying which fields from
each of the documents we're receiving in the stage using
project, we would like to include and pass along
to the next stage. One really cool thing we can
do with project, is insert computed fields. So, for
example, a ratio, which is what we're going to do
for this particular example we're working through. We might
also rename fields. And finally, we can do some pretty
substantial reshaping of the data, by doing something like
creating fields that hold subdocuments that are composed of what
were originally top level fields in the documents,
as they came into the stage using the project
operator. So let's go back to our code,
and look at how we're using project here. Remember,
the problem we're trying to solve here is,
addressing the question who has the highest followers to
friends ratio? So here, it's pretty straight forward, we're
simply pulling out the screen name field of the
user sub-document. Okay? And again, we use this
$ here, because rather than this being interpreted
as just a string literal, we're telling mongoDB
that we want the value. For each document
that's found in the user sub-document and in
the screen name field. Okay? So, in documents
that get passed along from this particular stage,
they will have a screen name field composed of
that value for each document that we received
as input here. Okay, now let's look at this
portion of the projected stage here. So we're going
to create a ratio field and documents that come
out of this particular stage. And that ratio
field is going to have the value of having
divided the followers count by the friends count, so
quite literally, calculating this ratio here. Again, remember friends,
in the documents we're looking at here, are the
number of people that I follow as opposed to
people who follow me. Okay, so again, diving into
the user sub-document, we're going to pull out the
followers account, and the friends account. Again making use
of the dollar operator here to indicate we actually
want the values of each of these. And then
we're going to use the divide operator to calculate the
ratio of these two values. It's that value
then, that will make up the value of the
ratio field in each document that gets passed
along from this stage using the project operator. Okay,
so when we get to this stage all
documents will have exactly two fields: ratio and screen
name. And then we're simply going to sort in
descending order based on ratio, and then of course,
limit to just the very first document that
we see. So let's run this. Okay, and again.
Our output from an aggregation inquiry is always
a single document. The results we're really interested in
are always in the result field, which is an array value field. Okay? So,
in this case, user in our tweets collection that has the highest
followers to friends ratio, is a user called Twitterific.
' Kay, turns out this is actually a Twitter application,
and even today if you look at Twitterific's page on Twitter,
you'll see that they have something on the order of nearly
half a million followers. But they only follow about 14 people,
so their followers to friends count ratio is still extremely high.
So again, in this example, we focused on the $ match
operator, which is just a filter, the $project operator, which is
a shaping operator, we actually have lots of things that we
can do here. And the sort and limit operators. So
in this case we've got four stages of our pipeline.
Now one thing before I wrap this up, is I
just want to quickly point out that we can build a
variety of expressions using the Project operator. If we take
a look at the MongoDB documentation, there are a number
of arithmetic operators that we can apply, as well as
a number of string operators, date operators and so on.
So this is the aggregation expression operators page in the docs. I encourage
you to look here for more information on the different types of operators
that are available to you when working with Project, as well as the
other aggregation framework operators. See the instructor
notes for a link to this page.
حسنًا، أود الآن انتهاز هذه الفرصة
والتحدث عن عامل تشغيل المشروع. فيوجد أمران يتعين
ملاحظتهما فيما يتعلق بالمشروع، حيث يمكننا استخدام المشروع
لتضمين حقول من المستند الأصلي. تذكر أن المشروع يتعامل مع
البيانات في مستند واحد كل مرة. ونحن بصدد
إجراء مهمة تشكيل من خلال المشروع. فمن
أبسط نماذج التشكيل هو تحديد الحقول
من كل مستند من المستندات التي نتلقاها في المرحلة باستخدام
المشروع، حيث نريد تضمين هذه الحقول ومرورها عبر المرحلة
التالية. من الأشياء الرائعة التي يمكننا
،إجراؤها من خلال المشروع هو إدراج حقول محسوبة. على سبيل المثال
نحن بصدد حساب النسبة
في هذا المثال تحديدًا. قد نعمد أيضًا إلى
إعادة تسمية الحقول. وأخيرًا، يمكننا إعادة تشكيل
البيانات على نطاق واسع، وذلك من خلال إجراء شيء
كإنشاء حقول تحتوي على مستندات فرعية مؤلفة مما
،كان في الأصل عبارة عن حقول للمستوى العلوي في المستندات
حيث وصلت إلى هذه المرحلة باستخدام عامل تشغيل
المشروع. حسنًا، لنرجع إلى التعليمة البرمجية الواردة لدينا
ونلقِ نظرة على كيفية استخدام المشروع هنا. تذكروا أن
المشكلة التي نحن بصدد حلها هنا تكمن في
توجيه سؤال: من يتمتع بأعلى نسبة من المتابعين إلى
الأصدقاء؟ إذًا، من السهل
استخراج حقل اسم الشاشة من المستند الفرعي
للمستخدم. مفهوم؟ وأكرر أننا نستخدم رمز
$ الوارد هنا، وذلك لأننا بدلاً من تفسير هذا الرمز
على أنه قيمة حرفية لسلسلة، نخبر MongoDB
أننا نريد قيمة كل مستند
موجود في مستند فرعي للمستخدم وحقل
اسم الشاشة. مفهوم؟ ستشتمل المستندات
التي يتم تمريرها خلال هذه المرحلة تحديدًا
على حقل screen name المتضمن
تلك القيمة لكل مستند تلقيناه
كإدخال هنا. حسنًا، لنلقِ نظرة الآن على هذا
المقطع من المرحلة المعروضة هنا. إذًا، سنعمد إلى
إنشاء حقل النسبة والمستندات الناشئة
عن هذه المرحلة تحديدًا. سيشتمل حقل النسبة
هذا على القيمة الناتجة عن
،تقسيم عدد المتابعين بالنسبة إلى عدد الأصدقاء
مما يؤدي إلى حساب هذه النسبة على النحو الوارد هنا بدقة. مرة أخرى، تذكروا أن الأصدقاء
الواردين في المستندات التي نلقي نظرة عليها هنا يمثلون
عدد الأشخاص الذين أتابعهم في مقابل
الأشخاص الذين يتابعونني. حسنًا، بالتعمق مرة أخرى في
المستند الفرعي للمستخدم، سنعمد إلى استخراج
حساب المتابعين وحساب الأصدقاء. ونعاود استخدام عامل تشغيل رمز
عملة الدولار هنا للإشارة إلى أننا
،نريد قيمة كل من هذين الحسابين. بعد ذلك
سنستخدم عامل تشغيل التقسيم لحساب
نسبة هاتين القيمتين. إذًا، فتلك القيمة
هي التي ستمثل قيمة
حقل النسبة في كل مستند يتم تمريره عبر هذه المرحلة
،باستخدام عامل تشغيل المشروع. حسنًا
فعند الوصول إلى هذه المرحلة، ستشتمل كل
المستندات على حقلين: هما حقلا النسبة
واسم الشاشة. ثم سنعمد بكل سهولة إلى الفرز
بترتيب تنازلي استنادًا إلى النسبة، ثم بالطبع سنقصر اختيارنا
على المستند الأول فقط
.الظاهر لدينا. إذًا، لنشغِّل هذا. حسنًا، مرة أخرى
دائمًا ما تكون المخرجات الناتجة عن استعلام aggregation
مستندًا فرديًا. ودائمًا ما تكون النتائج التي تمثل لنا أهمية
،موجودة في حقل النتيجة، وهو حقل قيمة صفيف. مفهوم؟ ففي هذه الحالة الماثلة
المستخدم الوارد في مجموعة التغريدات والذي يتمتع بأعلى نسبة من
.المتابعين إلى الأصدقاء يحمل اسم Twitterific
،حسنًا، فإن هذا الاسم يمثل فعليًا أحد تطبيقات Twitter
،وكذلك لو ألقيت نظرة اليوم على صفحة Twitterific
فستلاحظ أنها تشتمل على شيء يشهد إقبالاً يقرب من
،نصف مليون متابع. ولكنهم لا يتابعون سوى 14 شخصًا تقريبًا
.إذ لا تزال نسبة متابعيهم إلى عدد أصدقائهم مرتفعة إلى حد كبير
وأكرر أننا نركز في هذا المثال على عامل تشغيل
$ match الذي لا يُعد سوى عامل تصفية وعامل تشغيل project$ الذي يُعد
عامل تشغيل التشكيل، كما يمكننا فعليًا إجراء العديد من
الأشياء هنا. وكذلك عاملا تشغيل الفرز والتحديد. ففي
.هذه الحالة الماثلة، توجد لدينا أربعة مراحل للمسار
هناك شيء أخير قبل ختام حديثنا، وهو أنني
أريد الإشارة سريعًا إلى إمكانية إنشاء
مجموعة متنوعة من التعبيرات باستخدام عامل تشغيل Project. إذا ألقينا نظرة
على وثائق MongoDB، فسنجد عددًا
من المشغلات الحسابية التي يمكننا تطبيقها وكذلك
.عددًا من مشغلات السلسلة ومشغلات التاريخ وغيرها
فهذه هي صفحة مشغلات تعبير aggregation الموجودة في المستندات. أحثك على
الاطلاع هنا لمعرفة المزيد من المعلومات حول أنواع المشغلات المختلفة
المتاحة لديك عند التعامل مع عامل تشغيل Project وكذلك
غيره من مشغلات إطار عمل aggregation. راجع ملاحظات
.المدرب للحصول على رابط إلى هذه الصفحة
Muito bem. Agora, vamos verificar isso
e falar sobre o operador project. Algumas coisas
a serem observadas sobre o project. Podemos usar o project para
incluir campos a partir do documento original. Lembre-se de que o project trabalha
com os dados em um único documento de cada vez. E,
essencialmente, estamos definindo o formato com o project. Por isso, o
modo mais simples de definir o formato é simplesmente especificar quais campos de
cada um dos documentos que estamos recebendo neste estágio
usando project que gostaríamos de incluir e passar
para o próximo estágio. Uma coisa realmente bacana que podemos
fazer com o project é inserir campos calculados. Por exemplo,
uma proporção, que é o que faremos neste
exemplo em particular no qual estamos trabalhando. Também
podemos renomear campos. E, por fim, podemos redefinir o formato
dos dados de modo significativo fazendo algo como
criar campos que têm subdocumentos compostos do que
eram, originalmente, campos de nível superior nos documentos,
pois passaram para o estágio usando o operador
project. Vamos voltar para o nosso código
e verificar como estamos usando o project aqui. Lembre-se de
que o problema que estamos tentando resolver aqui é
responder à pergunta: quem tem a maior proporção de
seguidores por amigos? Aqui é bastante direto. Vamos
apenas extrair o campo screen_name do
subdocumento user. Certo? E, de novo, usamos este
cifrão aqui porque, em vez disto ser interpretado
como apenas uma string literal, estamos informando ao mongoDB
que queremos o valor de cada documento
encontrado no subdocumento user e no
campo screen_name. Certo? Assim, os documentos
passados a partir deste estágio em particular
terão um campo screen_name composto desse
valor para cada documento recebido
como entrada aqui. Certo. Agora, vamos analisar esta
parte do estágio do project aqui. Vamos criar um
campo ratio nos documentos que são
obtidos neste estágio em particular. O campo ratio
terá o valor da divisão
de followers_count por friends_count. Desse modo,
literalmente, calculando esta proporção aqui. Novamente, lembre-se de que friends,
nos documentos que estamos analisando aqui, refere-se ao
número de pessoas que eu sigo em oposição às
pessoas que me seguem. Então, de novo, detalhando o
subdocumento user, vamos extrair os valores de
followers_count e friends_count. Usamos novamente
o operador de cifrão aqui para indicar que, na verdade,
queremos os valores de cada um deles. Em seguida,
vamos usar o operador divide para calcular a
proporção desses dois valores. É esse valor
que irá compor o valor do campo
ratio em cada documento passado a partir
deste estágio usando o operador project. Muito bem.
Quando chegarmos a este estágio, todos
os documentos terão exatamente dois campos: ratio e
screen_name. Em seguida, vamos apenas classificar em
ordem decrescente com base em ratio e, é claro,
limitar apenas ao primeiro documento
que vemos. Vamos executar isto. Certo. E novamente,
nossa saída a partir de uma consulta de agregação é sempre
um único documento. Os resultados em que estamos realmente interessados
estão sempre no campo result, que é um campo de valor de array. Certo? Então,
neste caso, o usuário em nossa coleção de tweets que tem a maior
proporção de seguidores por amigos é um usuário chamado Twitterific.
Acontece que, na verdade, esse é um aplicativo do Twitter e,
mesmo hoje, se verificar a página de Twitterific no Twitter,
você verá que ele tem, aproximadamente,
meio milhão de seguidores. Mas ele segue apenas 14 pessoas;
por isso, sua proporção de seguidores por amigos ainda é extremamente alta.
Novamente, neste exemplo, nos concentramos no operador $match,
que é apenas um filtro, no operador $project, que é
um operador de definição de formato e com o qual podemos fazer
várias coisas. E os operadores sort e limit. Dessa forma,
neste caso, temos quatro estágios em nosso pipeline.
Agora, antes de concluir, eu quero apenas
destacar rapidamente que podemos criar uma grande
variedade de expressões usando o operador Project. Se verificarmos
a documentação do MongoDB, existem vários
operadores aritméticos que podem ser aplicados, bem como
vários operadores de string, operadores de datas, e assim por diante.
Então, esta é a página de operadores de expressão de agregação nos documentos. Eu incentivo
você a buscar aqui mais informações sobre os diferentes tipos de operadores
que estão disponíveis ao trabalhar com Project, além de
outros operadores de framework de agregação. Consulte as Notas
do instrutor para obter um link para esta página.
现在
我要继续讲一下投影运算符
在投影中 需要注意的几点是
我们可以利用投影来包括原文件中的域
记住 投影每次只能处理一个文件
我们其实是在利用投影进行数据构形
最简单的构形就是
在使用投影的阶段接收到的各文件中
设定我们想要包括哪一个域并将其传递给下一个阶段
利用投影
我们可以插入计算域
例如 比例 值
在这里 我们就要针对这个示例计算比例
我们还可以对域进行重命名
最后 我可以进行大规模的数据构形
为此 我可以创建含有子文件的域
这些子文件是在它们进入使用投影运算符的阶段时
由文件中的高级域构成的
我们再回来看一下代码
看看我们是如何使用投影的
记住 我们在这里要解决的问题是
找出被关注人数与朋友数比例最高的用户
这里的代码很直白
我们就是从用户子文件中抽取网名域
同样地 我们在这里使用了美元符号
因为 它不应该被视为字符串
我们告诉 mongoDB
我们想要的是
在用户子文件的网名域中
找到每个文件的值
所以 这个阶段传递出的每个文件
都会拥有一个网名域
这个域是由每个输入文件的值构成的
现在 我们来看一下
投影阶段的这一部分
我们要创建的是
这个阶段输出的比例域和文件
而这个比例域的值就是
朋友数除以被关注人数的值
也就是 在这里计算这个值
记住 在我们查看的这些文件中
朋友是我关注的人数 而不是关注我的人
我们再次浏览用户子文件
我们要抽出被关注人的数量
以及朋友的数量
这里同样要利用美元运算符
表示我们想要的是这些项的值
然后 我们要用除运算符
来计算两个值的比例
这个值会构成
使用投影运算符的这个阶段输出的
各文件的比例域值
当我们到达这一阶段时
所有文件都会拥有两个域 即比例域和网名域
然后 我们要根据比例
将它们按降序排列
之后 将结果限制为我们看到的第一个文件
我们运行一下这个代码
同样地 聚合查询的输出始终是一个单独的文件
我们想要的结果
总会出现在结果域中 它是一个数组值域
在这里的推文集合中
被关注人数与朋友数比例最高的用户是 Twitterific
其实 这是一个推特应用
即使你现在查看 Twitterific 在推特上的页面
你也会发现 关注它的人大概有近50万人
但它只关注了14个人
所以 它的被关注人数与朋友数比例很高
在这个例子中 我们仍关注了 $match 运算符 它是一个过滤器
还有 $project 运算符 它属于构形运算符
我们可以进行的运算还有很多种
这里还有排序和限制运算符
所以 在这里 我们的管道有四个阶段
在结束之前
我还要说一点
我们可以利用投影运算符进行多种表达
如果我们看一下 MongoDB 的文件
这里有很多可以使用的算数运算符
以及字符串运算符和日期运算符等等
这是文件中聚合表达运算符的页面
我希望你能在这里
查找在使用投影时可以运用的不同运算符
以及其它的聚合框架运算符
讲师注释中有这个页面的链接