Using CheatSheets To Apply Best Practices

Mongodb Cheatsheet

Mongodb Cheatsheet

1.1 Mongodb Operation

Name Summary
Connect to mongodb mongo 192.168.75.108:12345/d_2003 -u u_2003 -p XXXX
Start mongo mongod --config /etc/mongod.conf
Stop mongo kill -15 <pid>; mongo --eval "db.getSiblingDB('admin').shutdownServer()"
Mongo script get parameters mongo –eval “var day=’2013-07-26′” localhost:27017/shopex mongojs/update-index.js
Mongo data folder /var/lib/mongodb/journal
Export to json file mongoexport --db shopex --collection order --out collection.json
Import json file mongoimport --upsert --db shopex --collection order --file collection.json

1.2 Mongodb Basic

Name Summary
Remove table db.kvstore.remove()
define stored procedure db.system.js.save({_id:"addNumbers", value:function(x, y){ return x + y; }})
view stored procedure db.system.js.find()
call stored procedure db.eval('addNumbers(3, 4.2)')
Create record db.users.insert({"name":{"first":"refactor","last":"refactor2"},"age":24})
Update record db.users.update({"age":30}, {$set:{"age":31}});
Delete by filtering db.users.remove({"age":30})
Loop cusror while(s.hasNext()) printjson(s.next());
Loop array i=0; while(i < s.length) printjson(s[i++]);

1.3 Mongodb Query

Name Summary
Basic query db.users.find({“name”:{“first”:”refactor”,”last”:”refactor2″}})
Basic query db.users.find({“name.first”:”refactor”})
great than / or equal db.users.find({“age”:{“$gte”:20}})
not equal db.users.find({“age”:{“$ne”:31}})
exists db.users.find({“age”:{“$exists”:true}})
in db.users.find({“age”:{“$in”:[21,24]}})
not in db.users.find({“age”:{“$nin”:[21,23]}})
or db.users.find({“$or”:[{“name.last”:”another”}, {“age”:31}]})
Count matched records db.order.find({“created”:{“$regex”:”2013-07-12.*”}}).count()
  db.users.find({“age”:{“$nin”:[21,23]}}).count()
query by offset db.users.find({“age”:{“$nin”:[21,23]}}).skip(1).limit(2)
sort db.users.find().sort({“age”:24});
reverse order db.users.find().sort({“name.last”: -1})
  db.users.find().forEach( function(u) { printjson(u); } );
mod 20 db.users.find({“age”:{“$mod”:[20,4]}})
Parse string to float parseFloat(v.availableConfirmFee, 10);
filter by “like” db.taobao.find({“created”:/2013-07-12.*/})
  db.order.find({“created”:/2013-07-14.*/, “num”:{“$exists”:false}}).forEach( function(u) { printjson(u.tid); } );
  db.order.find({“created”:{“$regex”:day}}).count();
  db.order.distinct(“buyerNick”, {“created”:{“$regex”:day}}).length

1.4 More Resources

License: Code is licensed under MIT License.




Leave a Reply

Your email address will not be published. Required fields are marked *