Skip to content

Instantly share code, notes, and snippets.

my $client = MongoDB->connect();
my $coll = $client->ns("test.foo");
# do insert with number-like strings inserted as numbers
{
my $coll2 = $coll->with_codec( prefer_numeric => 1 );
$coll2->insert( answer => "42" ); # inserted as numeric 42
}
my $client = MongoDB->connect();
my $coll = $client->ns("test.foo");
# do insert with w:majority
{
my $coll2 = $coll->clone( write_concern => { w => 'majority' } );
$coll2->insert( $doc );
}
# WRONG WAY IS FATAL
$client = MongoDB->connect()
$client->authenticate("foo", "username", "sekret");
# RIGHT WAY
$client = MongoDB->connect("mongodb://username:sekret@localhost/foo");
my $client = MongoDB->connect();
my $coll = $client->ns("test.foo");
# assume first operation fails due to network error
eval {
$coll->insert( $doc );
};
warn $@ if $@;
# next operation automatically reconnects to MongoDB
# RIGHT WAY
my $client = MongoDB->connect();
eval {
# do work
};
if ( $@ ) {
die "Error doing work: $@";
}
# WRONG WAY
my $client;
if ( eval { $client = MongoDB->connect() } ) {
# do work
}
else {
die "MongoDB not available!";
}
# REPLICA SET (discovers other nodes)
my $client = MongoDB->connect(
"mongodb://h1.example.com/?replicaSet=myset"
);
# DIRECT CONNECTION
my $direct = MongoDB->connect(
"mongodb://h1.example.com/"
);
use MongoDB;
# OLD WAY
my $client = MongoDB::MongoClient->new(
host => "mongodb://h1.example.com/"
);
# NEW WAY
my $client = MongoDB->connect("mongodb://h1.example.com/");
db.collection(‘docs’).find({a:1}).limit(1).skip(100).toArray(function(err, docs) {
console.dir(err);
console.dir(docs);
});
{ itemId: 2, recom: [ { itemId: 32, weight: 36},
{ itemId: 158, weight: 23},
… ] }