Skip to content

Instantly share code, notes, and snippets.

ReplSetConnection.new(['db1.app.com'], ['db2.app.com'],
:rs_name => "myapp")
# To compile from the root of the c driver
scons
gcc -static -std=c99 -Wall query.c -I./src -L. -lbson -lmongoc -o query
require 'rubygems'
require 'mongoid'
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db("mongoid")
end
class Event
include Mongoid::Document
include Mongoid::Timestamps
#include "bson.h"
#include "mongo.h"
#include <stdio.h>
void main() {
bson b;
bson_buffer bb;
bson_buffer_init( &bb );
bson_append_string( &bb, "uid", "123456789");
// Compile this as follows:
// javac -classpath mongo.jar:bson.jar:. Perf.java
// Then run it like this:
// time java -classpath mongo.jar:bson.jar:. Perf
import com.mongodb.Mongo;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBList;
import com.mongodb.DBObject;
MongoDB Aggregation
Min and Max
db.posts.find({}).sort({x: 1}).limit(1) return the post with the smallest value for x
db.posts.find({}).sort({x: -1}).limit(1) return the post with the largest value for x
Note: min and max queries are most efficient with an index on the field being sorted on.
Count
db.posts.count(selector) count the number of posts matching the given selector
db.posts.count({}) count the total number of posts
MongoDB Aggregation
Min and Max
db.posts.find({}).sort({x: 1}).limit(1) return the post with the smallest value for x
db.posts.find({}).sort({x: -1}).limit(1) return the post with the largest value for x
Note: min and max queries are most efficient with an index on the field being sorted on.
Count
db.posts.count(selector) count the number of posts matching the given selector
db.posts.count({}) count the total number of posts
# with multiple collections + commands for renaming back the collections
require 'mongo'
# Stop writing to your database.
# Then, for each collection:
# Specify the DB and COLLECTION you want to convert.
# Will insert all modified documents into a new collection
# called 'new_' + old_collection_name.
# Then you can delete the old collection and rename the new one
class Hash
def prepare(start=nil)
h = {}
self.keys.each do |key|
key_name = start ? "#{start}.#{key}" : key
if self[key].is_a?(Hash)
h.merge!(self[key].prepare(key_name))
else
h[key_name] = self[key]
require 'rubygems'
require 'rack'
require 'mongo'
require 'logger'
$connection = Mongo::Connection.new( "genesis.mongohq.com", 27017, :pool_size =>
10, :timeout => 2, :logger => Logger.new( "mongo_rack.log" ) )
$db = $connection.db( "test" )
$db.authenticate('user', 'password')
$db['fs.files'].remove
$db['fs.chunks'].remove