Skip to content

Instantly share code, notes, and snippets.

@wertyoo
Last active December 19, 2018 15:54
Show Gist options
  • Save wertyoo/b9245ccb646d5990bcc4c8d26fd12440 to your computer and use it in GitHub Desktop.
Save wertyoo/b9245ccb646d5990bcc4c8d26fd12440 to your computer and use it in GitHub Desktop.
MongoDB Cheat Sheet

Local Mongo

  • Run mongod:
mongod --dbpath D:\NICK\Mongo\data --port 27017 --storageEngine wiredTiger
  • Create admin, site root users
use admin
db.createUser( {
  user: "adminuser",
 pwd: "user",
 roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
});
db.createUser( {
 user: "siterootadmin",
 pwd: "siteroot",
 roles: [ { role: "root", db: "admin" } ]
});
  • Create new db and add user
use mydb
db.createUser( {
 user: "mydbadmin", 
 pwd: "mydb",
 roles:[ { role: "dbOwner", db: "inv" } ]
});
  • Create collection:
db.createCollection("mycol")
  • Insert Doc via CLI
db.mycol.insert({"City":"Houma","State":"LA","ZipCode":"70360"})
  • Insert Doc via JSON file (new cmd window)
mongoimport --db inv --collection plants --file example1.json
  • Insert Doc via a JSON Array file (shorthand params)
mongoimport --jsonArray -d test -c docs --file example2.json
  • Set a variable - set to first file in current directory
myvar = "myvar"
  • Run a js script
load("myscript.js")
  • Print out json from JS script (any method that returns a cursor)
cursor = db.mycollection.find({})
while (cursor.hasNext()) {
  printjson(cursor.next());
}
  • List all files in current dir
ls()

Node JS

cursor = useDb.collection('millions').find().limit(limit).batchSize(arraySize);

for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
    counter++;
}

Quick Links

Comparing data

Aggreate Pipeline Help

Dump and Restore

Performance Optimization

Third Party Solutions

Lookup

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment