Skip to content

Instantly share code, notes, and snippets.

@victormejia
Last active August 29, 2015 13:57
Show Gist options
  • Save victormejia/9676928 to your computer and use it in GitHub Desktop.
Save victormejia/9676928 to your computer and use it in GitHub Desktop.
List of MondoDB commands I'm keeping track of as I go through the Tuts+ Learning MongoDB course https://tutsplus.com/course/learning-mongodb/.

Creating Databases, Collections, Documents

show databases

show dbs

connect to (or create) database

use dbname

insert new object (collection automatically created)

db.collection_name.insert(obj)

save (if present, then update, otherwise insert)

db.collection_name.save(obj)

all documents

db.collection_name.find()

db.collection_name.find().forEach(printjson)

Object IDs

view object id created by mongodb

db.collection_name.find()[0]._id.getTimestamp()

create ids using counter

function counter(name) {
    var ret = db.counters.findAndModify({query:{_id:name}, update:{$inc : {next:1}}, "new" true, upsert: true});
    return ret.next;
}
db.collection_name.insert({ _id: counter("products"), name: "product 1"});

Relating Documents

db.collection_name.insert({title: "test", userId: related_obj._id])
var obj = db.collection_name.find()[2]
db.users.findOne({_id: obj.userId})

Finding Documents

all records (returns cursor obj)

db.collection.find()
db.collection.find().forEach(printjson)

find matching field (works with arrays)

db.collection.find({field_name: field_value})

find single document

db.collection.findOne({field: value })

choose fields

db.collection.find({field_name: value}, {field1: 1, field2: 1})
db.collection.find({field_name: value}, {field3: 0})
db.collection.find({field_name: value}, {field1: 1, field: 2: 1, _id: 0})

Operators

Greater than

db.collection.find({ field: { $gt: num } });

less than

db.collection.find({ field: { $gt: num } });

greater than or equal to

db.collection.find({ field: { $gte: num } });

combine

db.collection.find({ field: { $gt: num1, $lt: num2 } });

field in

 db.users.find( {'name.first': {$in: ['John', 'Jane'] }}, {'name.first': 1})

field not in

 db.users.find( {'name.first': {$nin: ['John', 'Jane'] }}, {'name.first': 1})

all values in field

db.links.find({tags: { $all: ['marketplace', 'code']}}, {title: 1, tags: 1, _id: 0})

not equal

db.links.find({tags: { $ne: 'code'}}, { title: 1, tags: 1 })

or

db.users.find( { $or: [ { 'name.first': 'John' }, { 'name.last' : 'Wilson' } ] });

nor

db.users.find( { $nor: [ { 'name.first': 'John' }, { 'name.last' : 'Wilson' } ] });

and

db.users.find( { $and: [ { 'name.first': 'John' }, { 'name.last' : 'Wilson' } ] });

exists

db.users.find({email: { $exists: true } }, { name: 1, _id: 0});

not

db.links.find( { favourites: { $not: {  $mod: [5, 0] } } }, { title: 1, favourites: 1, _id: 0})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment