|
| 1 | + |
| 2 | +=pod |
| 3 | + |
| 4 | +=head1 DATABASE COMMANDS |
| 5 | + |
| 6 | +=head2 MapReduce |
| 7 | + |
| 8 | +MapReduce is a powerful aggregation tool. (For traditional queries, you should |
| 9 | +use C<MongoDB::Collection::query>.) |
| 10 | + |
| 11 | +This example counts the number of occurences of each tag in a collection. Each |
| 12 | +document contains a "tags" array that contains zero or more strings. |
| 13 | + |
| 14 | + my $map = <<MAP; |
| 15 | + function() { |
| 16 | + this.tags.forEach(function(tag) { |
| 17 | + emit(tag, {count : 1}); |
| 18 | + }); |
| 19 | + } |
| 20 | + MAP |
| 21 | + |
| 22 | + my $reduce = <<REDUCE; |
| 23 | + function(prev, current) { |
| 24 | + result = {count : 0}; |
| 25 | + current.forEach(function(item) { |
| 26 | + result.count += item.count; |
| 27 | + }); |
| 28 | + return result; |
| 29 | + } |
| 30 | + REDUCE |
| 31 | + |
| 32 | + my $cmd = Tie::IxHash->new("mapreduce" => "foo", |
| 33 | + "map" => $map, |
| 34 | + "reduce" => $reduce); |
| 35 | + |
| 36 | + my $result = $db->run_command($cmd); |
| 37 | + |
| 38 | +See the MongoDB documentation on MapReduce for more information |
| 39 | +(L<http://dochub.mongodb.org/core/mapreduce>). |
| 40 | + |
| 41 | +=head1 UPDATING |
| 42 | + |
| 43 | +=head2 Positional Operator |
| 44 | + |
| 45 | +In MongoDB 1.3.4 and later, you can use positional operator, C<$>, to update |
| 46 | +elements of an array. For instance, suppose you have an array of user |
| 47 | +information and you want to update a user's name. |
| 48 | + |
| 49 | +A sample document in JavaScript: |
| 50 | + |
| 51 | + { |
| 52 | + "users" : [ |
| 53 | + { |
| 54 | + "name" : "bill", |
| 55 | + "age" : 60 |
| 56 | + }, |
| 57 | + { |
| 58 | + "name" : "fred", |
| 59 | + "age" : 29 |
| 60 | + }, |
| 61 | + ] |
| 62 | + } |
| 63 | + |
| 64 | +The update: |
| 65 | + |
| 66 | + $coll->update({"users.name" => "fred"}, {'users.$.name' => "george"}); |
| 67 | + |
| 68 | +This will update the array so that the element containing C<"name" => "fred"> |
| 69 | +now has C<"name" => "george">. |
0 commit comments