# Copyright 2010 - present MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # PODNAME: MongoDB::Examples # ABSTRACT: Some examples of MongoDB syntax __END__ =pod =encoding UTF-8 =head1 NAME MongoDB::Examples - Some examples of MongoDB syntax =head1 VERSION version v2.2.2 =head1 MAPPING SQL TO MONGODB For developers familiar with SQL, the following chart should help you see how many common SQL queries could be expressed in MongoDB. These are Perl-specific examples of translating SQL queries to MongoDB's query language. To see the mappings for JavaScript (or another language), see L. In the following examples, C<$db> is a L object which was retrieved by using C. See L, L and L for more on the methods you see below. =over =item C Implicit, can be done explicitly. =item C $db->get_collection( 'users' )->insert_one( { a => 1, b => 1 } ); =item C $db->get_collection( 'users' )->find; =item C $db->get_collection( 'users' )->find( { age => 33 } )->fields( { a => 1, b => 1 }); =item C $db->get_collection( 'users' )->find( { name => qr/Joe/ } ); =item C $db->get_collection( 'users' )->find->sort( { name => -1 } ); =item C my $indexes = $db->get_collection( 'users' )->indexes; $indexes->create_one( [ name => 1 ] ); =item C my $indexes = $db->get_collection( 'users' )->indexes; $indexes->create_one( [ name => 1, ts => -1 ] ); =item C $db->get_collection( 'users' )->find->limit(10)->skip(20); =item C $db->get_collection( 'users' )->find->limit(1); =item C $db->get_collection( 'users' )->find( { z => 3 } )->explain; =item C $db->get_collection( 'users' )->count_documents; =item C<< SELECT COUNT(*y) FROM users where age > 30 >> $db->get_collection( 'users' )->count_documents( { "age" => { '$gt' => 30 } } ); =item C. After executing the above aggregation query, C<$out> will contain a L, allowing us to iterate through result documents such as the following: ( { '_id' => 'Soho', 'num_coffeshops' => 23 }, { '_id' => 'Chinatown', 'num_coffeshops' => 14 }, { '_id' => 'Upper East Side', 'num_coffeshops' => 10 }, { '_id' => 'East Village', 'num_coffeshops' => 87 } ) Note that L 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 C<$match> phase followed by a C<$group> phase. Use C<$match> to filter the documents in the collection prior to aggregation. The C<_id> field in the C<$group> stage specifies the key to group by; the C<$> in C<'$neighborhood'> indicates that we are referencing the name of a key. Finally, we use the C<$sum> operator to add one for every document in a particular neighborhood. There are other operators, such as C<$avg>, C<$max>, C<$min>, C<$push>, and C<$addToSet>, which can be used in the C<$group> phase and work much like C<$sum>. =head2 $project and $unwind Now let's look at a more complex example of the aggregation framework that makes use of the C<$project> and C<$unwind> pipeline operators. Suppose we have a collection called 'courses' which contains information on college courses. An example document in the collection looks like this: { '_id' => 'CSCI0170', 'name' => 'Computer Science 17', 'description' => 'An Integrated Introduction to Computer Science', 'instructor_id' => 29823498, 'instructor_name' => 'A. Greenwald', 'students' => [ { 'student_id' => 91736114, 'student_name' => 'D. Storch' }, { 'student_id' => 89100891, 'student_name' => 'J. Rassi' } ] } 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 C will do the trick: my $out = $db->get_collection('courses')->aggregate([ {'$unwind' => '$students'}, {'$project' => { '_id' => 0, 'course' => '$_id', 'student_id' => '$students.student_id', } }, {'$group' => { '_id' => '$student_id', 'courses' => {'$addToSet' => '$course'} } } ]); The output documents will each have a student ID number and an array of the courses in which that student is enrolled: ( { '_id' => 91736114, 'courses' => ['CSCI0170', 'CSCI0220', 'APMA1650', 'HIST1230'] }, { '_id' => 89100891, 'courses' => ['CSCI0170', 'CSCI1670', 'CSCI1690'] } ) The C<$unwind> stage of the aggregation query "peels off" 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 C<$project> stage then throws out unnecessary fields and keeps the ones we are interested in. It also pulls the student ID field out of its subdocument and creates a top-level field with the key C. Last, we group by student ID, using C<$addToSet> in order to add the unique courses for each student to the C array. =head2 $sort, $skip, and $limit The C<$sort>, C<$skip>, and C<$limit> pipeline operators work much like their companion methods in L. Returning to the previous students and courses example, suppose that we were particularly interested in the student with the ID that is numerically third-to-highest. We could retrieve the course list for that student by adding C<$sort>, C<$skip>, and C<$limit> phases to the pipeline: my $out = $db->get_collection('courses')->aggregate([ {'$unwind' => '$students'}, {'$project' => { '_id' => 0, 'course' => '$_id', 'student_id' => '$students.student_id', } }, {'$group' => { '_id' => '$student_id', 'courses' => {'$addToSet' => '$course'} } }, {'$sort' => {'_id' => -1}}, {'$skip' => 2}, {'$limit' => 1} ]); =head1 QUERYING =head2 Nested Fields MongoDB allows you to store deeply nested structures and then query for fields within them using I. For example, suppose we have a users collection with documents that look like: { "userId" => 12345, "address" => { "street" => "123 Main St", "city" => "Springfield", "state" => "MN", "zip" => "43213" } } If we want to query for all users from Springfield, we can do: my $cursor = $users->find({"address.city" => "Springfield"}); This will search documents for an "address" field that is a subdocument and a "city" field within the subdocument. =head1 UPDATING =head2 Positional Operator In MongoDB 1.3.4 and later, you can use positional operator, C<$>, 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. A sample document in JavaScript: { "users" : [ { "name" : "bill", "age" : 60 }, { "name" : "fred", "age" : 29 }, ] } The update: $coll->update_one({"users.name" => "fred"}, {'users.$.name' => "george"}); This will update the array so that the element containing C<"name" =E "fred"> now has C<"name" =E "george">. =head1 AUTHORS =over 4 =item * David Golden =item * Rassi =item * Mike Friedman =item * Kristina Chodorow =item * Florian Ragwitz =back =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2020 by MongoDB, Inc. This is free software, licensed under: The Apache License, Version 2.0, January 2004 =cut