
=pod

=head1 NAME

MongoDB::Examples - Some more advanced examples

=head1 DATABASE COMMANDS

=head2 Distinct

The distinct command returns all values for a given key in a collection.  For 
example, suppose we had a collection with the following documents (C<_id> value
ignored):

    { 'name' => 'a', code => 1 }
    { 'name' => 'b', code => 1 }
    { 'name' => 'c', code => 2 }
    { 'name' => 'd', code => "3" }

If we wanted to see all of values in the "code" field, we could run:

    my $result = $db->run_command([
       "distinct" => "collection_name",
       "key"      => "code",
       "query"    => {}
    ]);

Notice that the arguments are in an array, to ensure that their order is 
preserved.  You could also use a L<Tie::IxHash>.

C<query> is an optional argument, which can be used to only run C<distinct> on
specific documents.  It takes a hash (or L<Tie::IxHash> or array) in the same 
form as L<MongoDB::Collection/"find($query)">.

Running C<distinct> on the above collection would give you:

    {
        'ok' => '1',
        'values' => [
                      1,
                      2,
                      "3"
                    ]
    };

=head2 MapReduce

MapReduce is a powerful aggregation tool.  (For traditional queries, you should
use C<MongoDB::Collection::query>.)  

This example counts the number of occurences of each tag in a collection.  Each
document contains a "tags" array that contains zero or more strings.

    my $map = <<MAP;
    function() {
        this.tags.forEach(function(tag) {
            emit(tag, {count : 1});
        });
    }
    MAP
    
    my $reduce = <<REDUCE;
    function(prev, current) {
        result = {count : 0};
        current.forEach(function(item) {
            result.count += item.count;
        });
        return result;
    }
    REDUCE
    
    my $cmd = Tie::IxHash->new("mapreduce" => "foo",
        "map" => $map,
        "reduce" => $reduce);
    
    my $result = $db->run_command($cmd);

See the MongoDB documentation on MapReduce for more information
(L<http://dochub.mongodb.org/core/mapreduce>).

=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({"users.name" => "fred"}, {'users.$.name' => "george"});

This will update the array so that the element containing C<"name" =E<gt> "fred"> 
now has C<"name" =E<gt> "george">.
