I can never seem to remember all the commands I need to build a simple Express API app using Mongo.
If anyone is reading this, please share how I can make this post more useful.
BASICS
Show Databases
List all of the available databases.
show dbs
Clear the console
cls
Show Collections
show collections
Show data in a database>collection and make it look pretty
db.system.users.find().pretty()
Create a database called Customers
If the database has been created, Mongo will simply switch you in.
use customers
CREATING STUFF
Create a collection
db.createCollection('customers')
Create a user
What's unique about MongoDB is that you can insert Javascript into the database without any issues.
//Create a user
db.createUser({
"user": "chrisaiv",
"pwd": "password",
"roles": [
{ role: "clusterAdmin", db: "admin" },
{ role: "readAnyDatabase", db: "admin" },
"readWrite"
]
},
{ w: "majority", wtimeout: 5000 }
)
INSERTING DATA
Insert data into a user
use customers
Add a customer with a first and last name
db.customers.insert({
first_name: "chris",
last_name: "aiv"
})
Append a lot of data into a customer
db.customers.insert({
first_name: "Peter",
age: 32,
address: {
street: "120 Main St",
city: "Chicago",
state: "Illinois",
zip: "38475"
},
phone: {
home: "5555555555",
work: "4444444444",
mobile: "3333333333"
},
services: [
{
service_id: "time warner"
},
{
service_id: "pge"
},
{
service_id: "moviepass"
}
],
services_count: 3
});
Append data to a customer
db.customers.insert({
first_name: "Billy",
last_name: "Corgan",
gender: "m"
})
Insert a Date
db.customers.insert({
first_name: "Bo",
last_name: "Diddley",
birthdate: new Date('December 30, 1928')
})
Insert multiple customers in one query
db.customers.insert([
{
first_name: "Jimmy",
last_name: "Hendrix"
},
{
first_name: "Jimmy",
last_name: "Page"
},
{
first_name: "Kurt",
last_name: "Cobain"
},
{
first_name: "Adrian",
last_name: "Belew"
},
{
first_name: "Billy",
last_name: "Corgan"
}
])
FINDING DATA
Find services from person on first name
db.customers.find({ first_name: "Peter"}, { services: 1})
Find services by name only
db.customers.find({ first_name: "Peter"}, { "services.service_id": 1})
Find me a single record of "billy" and only return the first name
db.customers.findOne(
{ first_name: /^billy$/i },
{ first_name: 1 }
)
Find all the males in the database
db.customers.find({
gender: "male"
})
Find males who either have m or male for gender and firstname is case insensitive
db.customers.find({
gender: /(m|male)/i, first_name: /^billy$/i
})
UPDATING DATA
Destructive Update > !!! BE VERY VERY CAREFUL
db.customers.update(
{ first_name: "Jimmy" },
{ last_name: "Hendrix"}
)
Gentel Update > Use this technique for updates
db.customers.update(
{ last_name: /^hendrix$/i },
{ $set: { first_name: "Jimmy" } }
)
Increment a value in a field
db.customers.update(
{ first_name: "Billy" },
{ $inc: { age: 1 }
}
)
Update or Insert a field using an object ID
db.customers.update(
{ _id: ObjectId("5669f625a0a8005d8c7aae31") },
{
$set: {
gender: "male",
age: 50,
birthdate: new Date("Aug 20, 1985")
}
}
)
Update a field using someones first name
db.customers.update(
{ first_name: "Jimmy" },
{
$set: {
gender: "male",
age: 50,
birthdate: new Date("Aug 20, 1985")
}
},
{ upsert: true }
)
Add to an existing document
db.customers.update(
{ first_name: "Jimmy" },
{ $push: {
services: {
service_id: 'hosting windows',
service_name: "windows hosting"
}
}
}
)
REMOVING DATA
Remove a field
db.customers.update(
{ last_name: "Page" },
{
$unset: { age: 1 }
}
)
Remove a customer (NEVER DO THIS)
//!!! DO NOT US THIS
db.customers.remove(
//!!! DO NOT US THIS
{ first_name: "Billy"}, true
)
Remove any customer above the age of 31
db.customers.remove(
{ age: { $gt: 31 } }
, true
)
DELETING DATA
Delete a collection
db.customers.drop()
SEARCH
How to search an array within an object
{
_id: 1,
name: { first: 'John', last: 'Backus' },
birth: new Date('Dec 03, 1924'),
death: new Date('Mar 17, 2007'),
contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
awards: [
{ award: 'National Medal',
year: 1975,
by: 'NSF' },
{ award: 'Turing Award',
year: 1977,
by: 'ACM' }
]
}
db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})
How to query child objects
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
Retrieve only the queried element in object array
I'd like to get the document (Document 1) only with the array that contains color=red:
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"shapes":[
{
"shape":"square",
"color":"blue"
},
{
"shape":"circle",
"color":"red"
}
]
},
{
"_id":ObjectId("562e7c594c12942f08fe4193"),
"shapes":[
{
"shape":"square",
"color":"black"
},
{
"shape":"circle",
"color":"green"
}
]
}
3 Possible Answers: $elemMatch
projection operator, $filter
aggregation operator, $unwind
operator, $redact
aggregation (good for large datasets).
Subscribe to new posts
Processing your application
Please check your inbox and click the link to confirm your subscription
There was an error sending the email