Skip to content

Instantly share code, notes, and snippets.

@mgomes1
Last active August 29, 2015 14:01
Show Gist options
  • Save mgomes1/60e288112552892679a0 to your computer and use it in GitHub Desktop.
Save mgomes1/60e288112552892679a0 to your computer and use it in GitHub Desktop.
MongoDB Examples
// FINDING OUR WAY
show dbs
use examples
show collections
// DATA LOADING
function loadData() {
db.users.insert([
{
name: 'john',
age: 25,
sections: [ 'news', 'world' ]
},
{
name: 'mary',
sections: [ 'sports', 'business' ]
},
{
name: 'lucy',
age: 29
}
])
print('OK!')
}
loadData()
// INSERT
// db.collection.insert(documents, options)
db.users.insert( { name: 'peter', age: 45 } )
db.users.insert( { name: 'anne', age: 29 } )
db.users.insert( { name: 'bill', age: 32 } )
db.users.insert( { name: 'bob', age: 50 } )
db.users.insert( { name: 'linda', age: 39, sections: [ 'politics' ] } )
// SELECT
// db.collection.find(<criteria>, <projection>)
db.users.find()
db.users.find( { age: { $eq: 29 } } )
db.users.find( { age: { $gt: 25 } } ).sort( { age: -1 } )
db.users.find( { age: { $gt: 25 } } ).sort( { age: -1 } ).limit(3).skip(1)
db.users.find( { age: { $gt: 25 } }, { name: 1 } ).sort( { age: -1 } ).limit(3).skip(1)
db.users.find( { age: { $gt: 25 } }, { sections: 0 } ).sort( { age: -1 } ).limit(3).skip(1)
// UPDATE
// db.collection.update(query, update, options)
db.users.update(
{ },
{ $set: { status: 'A' } }
)
db.users.update(
{ },
{ $set: { status: 'A' } },
{ multi: true }
)
db.users.update(
{ name: { $eq: 'john' } },
{ $set: { sections: [ 'entertainment', 'travel' ] } }
)
db.users.update(
{ name: { $eq: 'john' } },
{ $set: { name: 'john smith' },
$inc: { age: 10 },
$push: { sections: 'technology' } }
)
// DELETE
// db.collection.remove(query, options)
db.users.find( { age: { $lt: 35 } } )
db.users.update( { age: { $lt: 35 } }, { $set: { status: 'D' } }, { multi: true } )
db.users.find( {}, { _id: 0, name: 1, status: 1 } )
db.users.remove( { status: 'D' } )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment