%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home/opti/optisoftcom-new/perl/usr/man/man3/
Upload File :
Create Path :
Current File : /home/opti/optisoftcom-new/perl/usr/man/man3/MongoDB::Examples.3pm

.\" Automatically generated by Pod::Man 2.27 (Pod::Simple 3.28)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  \*(C+ will
.\" give a nicer C++.  Capital omega is used to do unbreakable dashes and
.\" therefore won't be available.  \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
.    ds C`
.    ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el       .ds Aq '
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{
.    if \nF \{
.        de IX
.        tm Index:\\$1\t\\n%\t"\\$2"
..
.        if !\nF==2 \{
.            nr % 0
.            nr F 2
.        \}
.    \}
.\}
.rr rF
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "MongoDB::Examples 3"
.TH MongoDB::Examples 3 "2018-11-30" "perl v5.16.3" "User Contributed Perl Documentation"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
MongoDB::Examples \- Some examples of MongoDB syntax
.SH "VERSION"
.IX Header "VERSION"
version v2.0.2
.SH "MAPPING SQL TO MONGODB"
.IX Header "MAPPING SQL TO MONGODB"
For developers familiar with \s-1SQL,\s0 the following chart should help you see how
many common \s-1SQL\s0 queries could be expressed in MongoDB.
.PP
These are Perl-specific examples of translating \s-1SQL\s0 queries to MongoDB's query
language.  To see the mappings for JavaScript (or another language), see
<http://docs.mongodb.org/manual/reference/sql\-comparison/>.
.PP
In the following examples, \f(CW$db\fR is a MongoDB::Database object which was
retrieved by using \f(CW\*(C`get_database\*(C'\fR. See MongoDB::MongoClient,
MongoDB::Database and MongoDB::Collection for more on the methods
you see below.
.ie n .IP """CREATE TABLE USERS (a Number, b Number)""" 4
.el .IP "\f(CWCREATE TABLE USERS (a Number, b Number)\fR" 4
.IX Item "CREATE TABLE USERS (a Number, b Number)"
.Vb 1
\&    Implicit, can be done explicitly.
.Ve
.ie n .IP """INSERT INTO USERS VALUES(1,1)""" 4
.el .IP "\f(CWINSERT INTO USERS VALUES(1,1)\fR" 4
.IX Item "INSERT INTO USERS VALUES(1,1)"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->insert_one( { a => 1, b => 1 } );
.Ve
.ie n .IP """SELECT a,b FROM users""" 4
.el .IP "\f(CWSELECT a,b FROM users\fR" 4
.IX Item "SELECT a,b FROM users"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq)\->find( { } )\->fields( { a => 1, b => 1 });
.Ve
.ie n .IP """SELECT * FROM users""" 4
.el .IP "\f(CWSELECT * FROM users\fR" 4
.IX Item "SELECT * FROM users"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find;
.Ve
.ie n .IP """SELECT * FROM users WHERE age=33""" 4
.el .IP "\f(CWSELECT * FROM users WHERE age=33\fR" 4
.IX Item "SELECT * FROM users WHERE age=33"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( { age => 33 } )
.Ve
.ie n .IP """SELECT a,b FROM users WHERE age=33""" 4
.el .IP "\f(CWSELECT a,b FROM users WHERE age=33\fR" 4
.IX Item "SELECT a,b FROM users WHERE age=33"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( { age => 33 } )\->fields( { a => 1, b => 1 });
.Ve
.ie n .IP """SELECT * FROM users WHERE age=33 ORDER BY name""" 4
.el .IP "\f(CWSELECT * FROM users WHERE age=33 ORDER BY name\fR" 4
.IX Item "SELECT * FROM users WHERE age=33 ORDER BY name"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( { age => 33 } )\->sort( { name => 1 } );
.Ve
.ie n .IP """SELECT * FROM users WHERE age>33""" 4
.el .IP "\f(CWSELECT * FROM users WHERE age>33\fR" 4
.IX Item "SELECT * FROM users WHERE age>33"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( { age => { \*(Aq$gt\*(Aq => 33 } } );
.Ve
.ie n .IP """SELECT * FROM users WHERE age<33""" 4
.el .IP "\f(CWSELECT * FROM users WHERE age<33\fR" 4
.IX Item "SELECT * FROM users WHERE age<33"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( { age => { \*(Aq$lt\*(Aq => 33 } } );
.Ve
.ie n .IP """SELECT * FROM users WHERE name LIKE ""%Joe%""""" 4
.el .IP "\f(CWSELECT * FROM users WHERE name LIKE ``%Joe%''\fR" 4
.IX Item "SELECT * FROM users WHERE name LIKE ""%Joe%"""
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( { name => qr/Joe/ } );
.Ve
.ie n .IP """SELECT * FROM users WHERE name LIKE ""Joe%""""" 4
.el .IP "\f(CWSELECT * FROM users WHERE name LIKE ``Joe%''\fR" 4
.IX Item "SELECT * FROM users WHERE name LIKE ""Joe%"""
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( {name => qr/^Joe/ } );
.Ve
.ie n .IP """SELECT * FROM users WHERE age>33 AND age<=40""" 4
.el .IP "\f(CWSELECT * FROM users WHERE age>33 AND age<=40\fR" 4
.IX Item "SELECT * FROM users WHERE age>33 AND age<=40"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( { age => { \*(Aq$gt\*(Aq => 33, \*(Aq$lte\*(Aq => 40 } } );
.Ve
.ie n .IP """SELECT * FROM users ORDER BY name DESC""" 4
.el .IP "\f(CWSELECT * FROM users ORDER BY name DESC\fR" 4
.IX Item "SELECT * FROM users ORDER BY name DESC"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find\->sort( { name => \-1 } );
.Ve
.ie n .IP """CREATE INDEX myindexname ON users(name)""" 4
.el .IP "\f(CWCREATE INDEX myindexname ON users(name)\fR" 4
.IX Item "CREATE INDEX myindexname ON users(name)"
.Vb 2
\&    my $indexes = $db\->get_collection( \*(Aqusers\*(Aq )\->indexes;
\&    $indexes\->create_one( [ name => 1 ] );
.Ve
.ie n .IP """CREATE INDEX myindexname ON users(name,ts DESC)""" 4
.el .IP "\f(CWCREATE INDEX myindexname ON users(name,ts DESC)\fR" 4
.IX Item "CREATE INDEX myindexname ON users(name,ts DESC)"
.Vb 2
\&    my $indexes = $db\->get_collection( \*(Aqusers\*(Aq )\->indexes;
\&    $indexes\->create_one( [ name => 1, ts => \-1 ] );
.Ve
.ie n .IP """SELECT * FROM users WHERE a=1 and b=\*(Aqq\*(Aq""" 4
.el .IP "\f(CWSELECT * FROM users WHERE a=1 and b=\*(Aqq\*(Aq\fR" 4
.IX Item "SELECT * FROM users WHERE a=1 and b=q"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( {a => 1, b => "q" } );
.Ve
.ie n .IP """SELECT * FROM users LIMIT 10 SKIP 20""" 4
.el .IP "\f(CWSELECT * FROM users LIMIT 10 SKIP 20\fR" 4
.IX Item "SELECT * FROM users LIMIT 10 SKIP 20"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find\->limit(10)\->skip(20);
.Ve
.ie n .IP """SELECT * FROM users WHERE a=1 or b=2""" 4
.el .IP "\f(CWSELECT * FROM users WHERE a=1 or b=2\fR" 4
.IX Item "SELECT * FROM users WHERE a=1 or b=2"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( { \*(Aq$or\*(Aq => [ {a => 1 }, { b => 2 } ] } );
.Ve
.ie n .IP """SELECT * FROM users LIMIT 1""" 4
.el .IP "\f(CWSELECT * FROM users LIMIT 1\fR" 4
.IX Item "SELECT * FROM users LIMIT 1"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find\->limit(1);
.Ve
.ie n .IP """EXPLAIN SELECT * FROM users WHERE z=3""" 4
.el .IP "\f(CWEXPLAIN SELECT * FROM users WHERE z=3\fR" 4
.IX Item "EXPLAIN SELECT * FROM users WHERE z=3"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->find( { z => 3 } )\->explain;
.Ve
.ie n .IP """SELECT DISTINCT last_name FROM users""" 4
.el .IP "\f(CWSELECT DISTINCT last_name FROM users\fR" 4
.IX Item "SELECT DISTINCT last_name FROM users"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->distinct( \*(Aqlast_name\*(Aq );
.Ve
.ie n .IP """SELECT COUNT(*y) FROM users""" 4
.el .IP "\f(CWSELECT COUNT(*y) FROM users\fR" 4
.IX Item "SELECT COUNT(*y) FROM users"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->count_documents;
.Ve
.ie n .IP """SELECT COUNT(*y) FROM users where age > 30""" 4
.el .IP "\f(CWSELECT COUNT(*y) FROM users where age > 30\fR" 4
.IX Item "SELECT COUNT(*y) FROM users where age > 30"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->count_documents( { "age" => { \*(Aq$gt\*(Aq => 30 } } );
.Ve
.ie n .IP """SELECT COUNT(age) from users""" 4
.el .IP "\f(CWSELECT COUNT(age) from users\fR" 4
.IX Item "SELECT COUNT(age) from users"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->count_documents( { age => { \*(Aq$exists\*(Aq => 1 } } );
.Ve
.ie n .IP """UPDATE users SET a=1 WHERE b=\*(Aqq\*(Aq""" 4
.el .IP "\f(CWUPDATE users SET a=1 WHERE b=\*(Aqq\*(Aq\fR" 4
.IX Item "UPDATE users SET a=1 WHERE b=q"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->update_many( { b => "q" }, { \*(Aq$set\*(Aq => { a => 1 } } );
.Ve
.ie n .IP """UPDATE users SET a=a+2 WHERE b=\*(Aqq\*(Aq""" 4
.el .IP "\f(CWUPDATE users SET a=a+2 WHERE b=\*(Aqq\*(Aq\fR" 4
.IX Item "UPDATE users SET a=a+2 WHERE b=q"
.Vb 1
\&    $db\->get_collection( \*(Aqusers\*(Aq )\->update_many( { b => "q" }, { \*(Aq$inc\*(Aq => { a => 2 } } );
.Ve
.ie n .IP """DELETE FROM users WHERE z=""abc""""" 4
.el .IP "\f(CWDELETE FROM users WHERE z=``abc''\fR" 4
.IX Item "DELETE FROM users WHERE z=""abc"""
.Vb 1
\&    $db\->get_database( \*(Aqusers\*(Aq )\->delete_many( { z => "abc" } );
.Ve
.SH "DATABASE COMMANDS"
.IX Header "DATABASE COMMANDS"
If you do something in the MongoDB shell and you would like to translate it to
Perl, the best way is to run the function in the shell without parentheses, which
will print the source.  You can then generally translate the source into Perl
fairly easily.
.PP
For example, suppose we want to use \f(CW\*(C`db.foo.validate\*(C'\fR in Perl.  We could
run:
.PP
.Vb 10
\&    > db.foo.validate
\&    function (full) {
\&        var cmd = {validate:this.getName()};
\&        if (typeof full == "object") {
\&            Object.extend(cmd, full);
\&        } else {
\&            cmd.full = full;
\&        }
\&        var res = this._db.runCommand(cmd);
\&        if (typeof res.valid == "undefined") {
\&            res.valid = false;
\&            var raw = res.result || res.raw;
\&            if (raw) {
\&                var str = "\-" + tojson(raw);
\&                res.valid = !(str.match(/exception/) || str.match(/corrupt/));
\&                var p = /lastExtentSize:(\ed+)/;
\&                var r = p.exec(str);
\&                if (r) {
\&                    res.lastExtentSize = Number(r[1]);
\&                }
\&            }
\&        }
\&        return res;
\&    }
.Ve
.PP
Next, we can translate the important parts into Perl:
.PP
.Vb 1
\&    $db\->run_command( [ validate => "foo" ] );
.Ve
.SS "Find-one-and-modify"
.IX Subsection "Find-one-and-modify"
The find-one-and-modify commands in MongoDB::Collection are similar to
update (or remove), but will return the modified document.  They can be
useful for implementing queues or locks.
.PP
For example, suppose we had a list of things to do, and we wanted to remove
the highest-priority item for processing.  We could do a
find and then a
delete_one, but that wouldn't be atomic
(a write could occur between the query and the remove).  Instead, we could
use find_one_and_delete:
.PP
.Vb 5
\&    my $coll = $db\->get_collection(\*(Aqtodo\*(Aq);
\&    my $next_task = $todo\->find_one_and_delete(
\&        {}, # empty filter means any document
\&        { sort => {priority => \-1} },
\&    );
.Ve
.PP
This will atomically find and pop the next-highest-priority task.
.PP
See <http://www.mongodb.org/display/DOCS/findAndModify+Command> for more
details on find-and-modify.
.SH "AGGREGATION"
.IX Header "AGGREGATION"
The aggregation framework is MongoDB's analogy for \s-1SQL GROUP BY\s0 queries,
but more generic and more powerful. An invocation of the aggregation framework
specifies a series of stages in a pipeline to be executed in order by
the server. Each stage of the pipeline is
drawn from one of the following so-called \*(L"pipeline operators\*(R":
\&\f(CW$project\fR, \f(CW$match\fR, \f(CW$limit\fR, \f(CW$skip\fR, \f(CW$unwind\fR, \f(CW$group\fR,
\&\f(CW$sort\fR, and \f(CW$geoNear\fR.
.PP
The aggregation framework is the preferred way of performing
most aggregation tasks. New in version 2.2, it has largely
obviated mapReduce <http://docs.mongodb.org/manual/reference/command/mapReduce/#dbcmd.mapReduce>,
and group <http://docs.mongodb.org/manual/reference/command/group/#dbcmd.group>.
.PP
See the MongoDB aggregation framework documentation for more
information (<http://docs.mongodb.org/manual/aggregation/>).
.ie n .SS "$match and $group"
.el .SS "\f(CW$match\fP and \f(CW$group\fP"
.IX Subsection "$match and $group"
The \f(CW$group\fR pipeline operator is used like \s-1GROUP BY\s0 in \s-1SQL.\s0 For example,
suppose we have a number of local businesses stored in a \*(L"business\*(R" collection. 
If we wanted to find the number of coffeeshops in each neighborhood, we
could do:
.PP
.Vb 6
\&    my $out = $db\->get_collection(\*(Aqbusiness\*(Aq)\->aggregate(
\&        [
\&            {\*(Aq$match\*(Aq => {\*(Aqtype\*(Aq => \*(Aqcoffeeshop\*(Aq}},
\&            {\*(Aq$group\*(Aq => {\*(Aq_id\*(Aq => \*(Aq$neighborhood\*(Aq, \*(Aqnum_coffeshops\*(Aq => {\*(Aq$sum\*(Aq => 1}}}
\&        ]
\&    );
.Ve
.PP
The \s-1SQL\s0 equivalent is \f(CW\*(C`SELECT neighborhood, COUNT(*) FROM business GROUP BY neighborhood WHERE type = \*(Aqcoffeeshop\*(Aq\*(C'\fR.
After executing the above aggregation query, \f(CW$out\fR will contain a
MongoDB::QueryResult, allowing us to iterate through result documents
such as the following:
.PP
.Vb 10
\&    (
\&         {
\&             \*(Aq_id\*(Aq => \*(AqSoho\*(Aq,
\&             \*(Aqnum_coffeshops\*(Aq => 23
\&         },
\&         {
\&             \*(Aq_id\*(Aq => \*(AqChinatown\*(Aq,
\&             \*(Aqnum_coffeshops\*(Aq => 14 
\&         },
\&         {
\&             \*(Aq_id\*(Aq => \*(AqUpper East Side\*(Aq,
\&             \*(Aqnum_coffeshops\*(Aq => 10
\&         },
\&         {
\&             \*(Aq_id\*(Aq => \*(AqEast Village\*(Aq,
\&             \*(Aqnum_coffeshops\*(Aq => 87
\&         }
\&    )
.Ve
.PP
Note that aggregate takes an array reference as
an argument. Each element of the array is document which specifies a stage
in the aggregation pipeline. Here our aggregation query consists of a
\&\f(CW$match\fR phase followed by a \f(CW$group\fR phase. Use \f(CW$match\fR to filter the
documents in the collection prior to aggregation. The \f(CW\*(C`_id\*(C'\fR field in the
\&\f(CW$group\fR stage specifies the key to group by; the \f(CW\*(C`$\*(C'\fR in \f(CW\*(Aq$neighborhood\*(Aq\fR
indicates that we are referencing the name of a key. Finally, we use the
\&\f(CW$sum\fR operator to add one for every document in a particular neighborhood.
There are other operators, such as \f(CW$avg\fR, \f(CW$max\fR, \f(CW$min\fR, \f(CW$push\fR, and
\&\f(CW$addToSet\fR, which can be used in the \f(CW$group\fR phase and work much like
\&\f(CW$sum\fR.
.ie n .SS "$project and $unwind"
.el .SS "\f(CW$project\fP and \f(CW$unwind\fP"
.IX Subsection "$project and $unwind"
Now let's look at a more complex example of the aggregation framework that
makes use of the \f(CW$project\fR and \f(CW$unwind\fR pipeline operators. Suppose
we have a collection called 'courses' which contains information on college
courses. An example document in the collection looks like this:
.PP
.Vb 11
\&    {
\&        \*(Aq_id\*(Aq => \*(AqCSCI0170\*(Aq,
\&        \*(Aqname\*(Aq => \*(AqComputer Science 17\*(Aq,
\&        \*(Aqdescription\*(Aq => \*(AqAn Integrated Introduction to Computer Science\*(Aq,
\&        \*(Aqinstructor_id\*(Aq => 29823498,
\&        \*(Aqinstructor_name\*(Aq => \*(AqA. Greenwald\*(Aq,
\&        \*(Aqstudents\*(Aq => [
\&            { \*(Aqstudent_id\*(Aq => 91736114, \*(Aqstudent_name\*(Aq => \*(AqD. Storch\*(Aq },
\&            { \*(Aqstudent_id\*(Aq => 89100891, \*(Aqstudent_name\*(Aq => \*(AqJ. Rassi\*(Aq }
\&        ]
\&    }
.Ve
.PP
We wish to generate a report containing one document per student that indicates
the courses in which each student is enrolled. The following call to
\&\f(CW\*(C`aggregate\*(C'\fR will do the trick:
.PP
.Vb 10
\&    my $out = $db\->get_collection(\*(Aqcourses\*(Aq)\->aggregate([
\&        {\*(Aq$unwind\*(Aq => \*(Aq$students\*(Aq},
\&        {\*(Aq$project\*(Aq => {
\&                \*(Aq_id\*(Aq => 0,
\&                \*(Aqcourse\*(Aq => \*(Aq$_id\*(Aq,
\&                \*(Aqstudent_id\*(Aq => \*(Aq$students.student_id\*(Aq,
\&            }
\&        },
\&        {\*(Aq$group\*(Aq => {
\&                \*(Aq_id\*(Aq => \*(Aq$student_id\*(Aq,
\&                \*(Aqcourses\*(Aq => {\*(Aq$addToSet\*(Aq => \*(Aq$course\*(Aq}
\&            }
\&        }
\&    ]);
.Ve
.PP
The output documents will each have a student \s-1ID\s0 number and an array of the
courses in which that student is enrolled:
.PP
.Vb 10
\&    (
\&        {
\&            \*(Aq_id\*(Aq => 91736114,
\&            \*(Aqcourses\*(Aq => [\*(AqCSCI0170\*(Aq, \*(AqCSCI0220\*(Aq, \*(AqAPMA1650\*(Aq, \*(AqHIST1230\*(Aq]
\&        },
\&        {
\&            \*(Aq_id\*(Aq => 89100891,
\&            \*(Aqcourses\*(Aq => [\*(AqCSCI0170\*(Aq, \*(AqCSCI1670\*(Aq, \*(AqCSCI1690\*(Aq]
\&        }
\&    )
.Ve
.PP
The \f(CW$unwind\fR stage of the aggregation query \*(L"peels off\*(R" elements of the courses
array one-by-one and places them in their own documents. After this phase completes,
there is a separate document for each (course, student) pair. The \f(CW$project\fR stage
then throws out unnecessary fields and keeps the ones we are interested in. It also
pulls the student \s-1ID\s0 field out of its subdocument and creates a top-level field
with the key \f(CW\*(C`student_id\*(C'\fR. Last, we group by student \s-1ID,\s0 using \f(CW$addToSet\fR in
order to add the unique courses for each student to the \f(CW\*(C`courses\*(C'\fR array.
.ie n .SS "$sort, $skip, and $limit"
.el .SS "\f(CW$sort\fP, \f(CW$skip\fP, and \f(CW$limit\fP"
.IX Subsection "$sort, $skip, and $limit"
The \f(CW$sort\fR, \f(CW$skip\fR, and \f(CW$limit\fR pipeline operators work much like their
companion methods in MongoDB::Cursor. Returning to the previous students and
courses example, suppose that we were particularly interested in the student with
the \s-1ID\s0 that is numerically third-to-highest. We could retrieve the course list for that
student by adding \f(CW$sort\fR, \f(CW$skip\fR, and \f(CW$limit\fR phases to the pipeline:
.PP
.Vb 10
\&    my $out = $db\->get_collection(\*(Aqcourses\*(Aq)\->aggregate([
\&        {\*(Aq$unwind\*(Aq => \*(Aq$students\*(Aq},
\&        {\*(Aq$project\*(Aq => {
\&                \*(Aq_id\*(Aq => 0,
\&                \*(Aqcourse\*(Aq => \*(Aq$_id\*(Aq,
\&                \*(Aqstudent_id\*(Aq => \*(Aq$students.student_id\*(Aq,
\&            }
\&        },
\&        {\*(Aq$group\*(Aq => {
\&                \*(Aq_id\*(Aq => \*(Aq$student_id\*(Aq,
\&                \*(Aqcourses\*(Aq => {\*(Aq$addToSet\*(Aq => \*(Aq$course\*(Aq}
\&            }
\&        },
\&        {\*(Aq$sort\*(Aq => {\*(Aq_id\*(Aq => \-1}},
\&        {\*(Aq$skip\*(Aq => 2},
\&        {\*(Aq$limit\*(Aq => 1}
\&    ]);
.Ve
.SH "QUERYING"
.IX Header "QUERYING"
.SS "Nested Fields"
.IX Subsection "Nested Fields"
MongoDB allows you to store deeply nested structures and then query for fields
within them using \fIdot-notation\fR.  For example, suppose we have a users
collection with documents that look like:
.PP
.Vb 9
\&    {
\&        "userId" => 12345,
\&        "address" => {
\&            "street" => "123 Main St",
\&            "city" => "Springfield",
\&            "state" => "MN",
\&            "zip" => "43213"
\&        }
\&    }
.Ve
.PP
If we want to query for all users from Springfield, we can do:
.PP
.Vb 1
\&    my $cursor = $users\->find({"address.city" => "Springfield"});
.Ve
.PP
This will search documents for an \*(L"address\*(R" field that is a subdocument and a
\&\*(L"city\*(R" field within the subdocument.
.SH "UPDATING"
.IX Header "UPDATING"
.SS "Positional Operator"
.IX Subsection "Positional Operator"
In MongoDB 1.3.4 and later, you can use positional operator, \f(CW\*(C`$\*(C'\fR, to update
elements of an array.  For instance, suppose you have an array of user
information and you want to update a user's name.
.PP
A sample document in JavaScript:
.PP
.Vb 12
\&    {
\&        "users" : [
\&            {
\&                "name" : "bill",
\&                "age" : 60
\&            },
\&            {
\&                "name" : "fred",
\&                "age" : 29
\&            },
\&        ]
\&    }
.Ve
.PP
The update:
.PP
.Vb 1
\&    $coll\->update_one({"users.name" => "fred"}, {\*(Aqusers.$.name\*(Aq => "george"});
.Ve
.PP
This will update the array so that the element containing \f(CW"name" => "fred"\fR
now has \f(CW"name" => "george"\fR.
.SH "AUTHORS"
.IX Header "AUTHORS"
.IP "\(bu" 4
David Golden <david@mongodb.com>
.IP "\(bu" 4
Rassi <rassi@mongodb.com>
.IP "\(bu" 4
Mike Friedman <friedo@friedo.com>
.IP "\(bu" 4
Kristina Chodorow <k.chodorow@gmail.com>
.IP "\(bu" 4
Florian Ragwitz <rafl@debian.org>
.SH "COPYRIGHT AND LICENSE"
.IX Header "COPYRIGHT AND LICENSE"
This software is Copyright (c) 2018 by MongoDB, Inc.
.PP
This is free software, licensed under:
.PP
.Vb 1
\&  The Apache License, Version 2.0, January 2004
.Ve

Zerion Mini Shell 1.0