Creating Databases, Collections, Documents
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)
db.collection_name.find()
db.collection_name.find().forEach(printjson)
view object id created by mongodb
db.collection_name.find()[0]._id.getTimestamp()
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"});
db.collection_name.insert({title: "test", userId: related_obj._id])
var obj = db.collection_name.find()[2]
db.users.findOne({_id: obj.userId})
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})
db.collection.findOne({field: value })
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})
db.collection.find({ field: { $gt: num } });
db.collection.find({ field: { $gt: num } });
db.collection.find({ field: { $gte: num } });
db.collection.find({ field: { $gt: num1, $lt: num2 } });
db.users.find( {'name.first': {$in: ['John', 'Jane'] }}, {'name.first': 1})
db.users.find( {'name.first': {$nin: ['John', 'Jane'] }}, {'name.first': 1})
db.links.find({tags: { $all: ['marketplace', 'code']}}, {title: 1, tags: 1, _id: 0})
db.links.find({tags: { $ne: 'code'}}, { title: 1, tags: 1 })
db.users.find( { $or: [ { 'name.first': 'John' }, { 'name.last' : 'Wilson' } ] });
db.users.find( { $nor: [ { 'name.first': 'John' }, { 'name.last' : 'Wilson' } ] });
db.users.find( { $and: [ { 'name.first': 'John' }, { 'name.last' : 'Wilson' } ] });
db.users.find({email: { $exists: true } }, { name: 1, _id: 0});
db.links.find( { favourites: { $not: { $mod: [5, 0] } } }, { title: 1, favourites: 1, _id: 0})