MongoDB Basic Usage Summary
- Comparison of DB structures
- Create Database and Collection
- Drop Database and Collection
- Insert Document
- Remove Document
- Basic Query
- Query Operator
- Query with matching Pattern
- Condition on the same element of array
- Sort, Skip, Limit
- Projection
- Distinct, Count
- Update (Upsert)
- Aggregation
- Conditional Aggregation
- Projection in Aggregation
- Index
- Query Plan
- Sharding in MongoDB
- Writing JavaScript
- Other Useful Methods
Comparison of DB structures
RDBMS | MongoDB |
---|---|
Database | Database |
Table | Collection |
Row | Document |
Primary Key of a collection: _id Field
Create Database and Collection
There is no need to explicitly create database. Database can be automatically created once you add a collection (i.e. table) to it, and db is a shell variable representing the current database.
> show databases
> use databasename
switched to db databasename
> db
databasename
> show databases
> use databasename
switched to db databasename
> db.createCollection('table')
{ "ok" : 1 }
> show databases;
databasename 0.000GB
Syntax | Explanation |
---|---|
use databasename | Switch to database ‘databasename’ |
db | Show current database |
show databases | List all databases |
db.getCollectionNames() | List all collections in current db |
show tables | List all collections in current db |
show collections | List all collections in current db |
db.createCollection(‘table’) | Create collection ‘table’ in current database |
Drop Database and Collection
> db.table.drop()
true
> show tables
> db.dropDatabase()
{ "dropped" : "databasename", "ok" : 1 }
> show databases
Syntax | Explanation |
---|---|
db.table.drop() | Drop collection ‘table’ |
db.dropDatabase() | Drop current database |
Insert Document
Syntax | Example |
---|---|
db.table.insert() | db.person.insert({"_id":1, "name":"john smith", "address": {"street": "123 maple", "city": "LA", "zip": 91989}}) |
db.table.insert({"_id": ObjectId(), …}) | db.person.insert({"_id": ObjectId(), "name": "john smith"}) |
db.table.insertMany([{…}, {…}]) | db.person.insertMany([{"name": "kevin small", "age": 35, "scores":[5, 6, 3]}, {"name": "mary lou", "scores":[5,8,2]}]) |
Note:
- Attributes with single quotes ’ ’ or omitted quotes are acceptable.
- Duplicate key of “_id” is not acceptable.
- ObjectId() is automatically used when you insert doncument without specifying “_id”.
- ObjectId() is created with a 12-byte hexademical value, with 4 bytes of seconds since 1970/1/1, 3 bytes of machine identifier, 2 bytes of process id, 3 bytes of counter starting with a random value.
E.g. 58250aec7c61126eba98db48 - db.table.insert([…]) can also take multiple docs.
Remove Document
Syntax | Example | Explanation |
---|---|---|
db.table.remove({}) | Remove all docs from the collection | |
db.person.remove({"age":{$gt:30}}) | Remove all docs whose “age” is over 30 |
Basic Query
Syntax | Example | Explanation |
---|---|---|
db.table.find() | db.person.find() | Return all docs in “person” collection |
db.table.find({…}) | db.person.find({"info.name":"kevin small"}) | Return all docs with the specified “name” in “info” attribute (Embedded Document) |
db.table.find().pretty() | db.person.find().pretty() | Pretty print |
Note: Quotes in embedded doc are required.
Query Operator
Comparison Operator | Explanation | Example |
---|---|---|
$lt, $gt, $lte, $gte | less than, greater than, less than or equal, greater than equal | db.person.find({"age": {$gt:25, $lt:30}}) |
$eq, $ne, $in, $all | Values of comparison operators are in array | db.person.find({age:{$in:[25,35]}}) |
Note:
- Values of comparison operators are in array.
- The second example means finding people whose ages are either 25 or 35.
db.person.find({"scores":{$gt: 20}})
The “scores” field is an array and at least one value of the array should satisfy the specified condition (i.e., > 20)
Logical Operator | Explanation | Example |
---|---|---|
$or, $and | Values of $or, $and are in array | db.person.find({$or:[{"name":"kevin small"}, {"age":{$gt: 25}}]}) ,db.person.find({$and: [{"name":/kevin/i}, {"age":25}]}) equivalent to db.person.find({"name":"kevin small", "age": {$gt: 25}}) |
$not | $not requires either a regex /…/ or a doc {…} | db.person.find({name: {$not: {$eq: "john"}}}) |
Note:
- ERROR:
– db.person.find({$not: {“name”: “david”}})
– $not cannot be a top‐level operator. db.person.find({scores: {$all: [2, 5]}})
equivalent todb.person.find({$and: [{scores: 2}, {scores: 3}]})
Query with matching Pattern
Syntax | Explanation | Example |
---|---|---|
db.table.find({ … : /…/ }) | Return all docs with the attribute matching the pattern in /…/ | db.person.find({"name":/Kevin/}) |
db.table.find({ … : /…/i }) | ‘i’ means case insensitive | db.person.find({"name":/Kevin/i}) |
db.table.find({ … : {$regex : /… /, $options: ‘i’ }}) | Equivalent to db.table.find({ … : /…/i }) | db.person.find({"name":{$regex: /Kevin/, $options:'i'}}) |
db.table.find({ … : {$not: /…/ }}) | Return all docs without pattern in /…/ in the attribute | db.person.find({"name": {$not: /john/i}}) |
Note: The last one also matches the docs without attribute “name”.
Condition on the same element of array
Syntax | Example | Explanation |
---|---|---|
db.table.find({ … : {$elemMatch: {…}}}) | db.person.find({"scores": {$elemMatch: {"midterm": "B", "score": {$gt: 90}}}}) | Return docs with “scores” satifying “midterm” is “B” and “score” is greater than 90 at the same time. |
Sort, Skip, Limit
Syntax | Example | Explanation |
---|---|---|
db.table.find()sort({ … : 1}) | db.person.find().sort({"age" : -1}) | Retrurn all docs with sorting by age descending (1 for ascending; -1 for descending) |
db.table.find().limit(…) | db.person.find().limit(10) | Return the first 10 docs |
db.table.find().skip(…).limit(…) | db.person.find().skip(2).limit(10) | Return the first 10 docs with skipping the first 2 |
Projection
Syntax | Example | Explanation |
---|---|---|
db.table.find({… : 1}) | db.person.find({"age" : {$ne : 25}}, {"_id": 0, "name":1, "age":1}) | Return only “name” and “age” that “age” is not 25 |
Note:
- "_id" will also be shown if it is not specified with 0.
- Only "_id " can be assigned with 0; this is wrong:
db.person.find({"age":{$ne:25}}, {"name":1, "age":0})
.
Distinct, Count
Syntax | Example | Explanation |
---|---|---|
db.table.distinct() | db.person.distince("age", {"age":{$gt:20}}) | Return all docs with distinct “age” with “age” over 20 |
db.table.distinct(…).length | db.person.distinct("age").length | Return the number of the query result |
Note: Wrong Syntax: db.table.find(…).distinct(…)
Syntax | Example | Explanation |
---|---|---|
db.table.count() | db.person.count({"age" : {$gt:25}}) | Return the number of the docs satisfying “age” is over 25 |
db.table.find(…).count() | db.person.find({"age":{$gt:25}}).count() | The same as above |
Note: Watch out for null values when using comparison oprators.
Update (Upsert)
Syntax | Example | Explanation |
---|---|---|
db.table.update({…}, {…}, …) | db.person.update({"age" : {$gt:25}}, {$set:{"status":"C", "gender":"M"}}, {multi:true}) | Update all docs setting “status” to “C” whose “age” is over 25 |
Note:
- If there is no attribute “status”, it will be an insert.
- If don’t use
$set
, it will be an overwriting. - If there is no
{multi:true}
, it will only update one document. db.table.updateMany(...)
is equivalent todb.table.update( ... , {multi:true})
.db.person.update({}, {$set: {"status":"C"}})
adds “status” attribute to all docs.
Syntax | Example | Explanation |
---|---|---|
db.table.update( … , {upsert:true}) | db.person.update({"age":25}, {$set:{"name":"jonny"}}, {upsert:true}) | Insert if attribute “name” not exists; if no doc with “age”=25, a new doc will be inserted with ObjectId() |
db.person.update({_id:2}, {$set:{"name":"jonny"}}, {upsert:true}) | If no doc with “_id”=2, a new doc with “_id”=2 will be inserted |
Syntax | Example | Explanation |
---|---|---|
db.table.update( … , {$unset: { … : … }}, {multi:true}) | db.person.update({}, {$unset:{"status":"C"}}) | Remove all “status” that is “C” in all docs |
Aggregation
Sample Collection for Aggregation:
> db.product.insertMany([{category:"cell",store:1,qty: 10}, {category:"cell",store:2,qty: 20}, {category:"laptop",store:1, qty: 10}, {category:"laptop",store:2, qty: 30}, {category:"laptop",store:2, qty: 40}])
Function | Example | Return |
---|---|---|
sum | db.product.aggregate({$group:{"_id":"$category", "total":{$sum:"$qty"}}}) | { “_id” : “laptop”, “total” : 80 } { “_id” : “cell”, “total” : 30 } |
sum on multiple fields | db.product.aggregate({$group:{"_id":{"cat":"$category", "st":"$store"}, "total":{$sum:"$qty"}}}) | { “_id” : { “cat” : “laptop”, “st” : 1 }, “total” : 10 } { “_id” : { “cat” : “laptop”, “st” : 2 }, “total” : 70 } { “_id” : { “cat” : “cell”, “st” : 2 }, “total” : 20 } { “_id” : { “cat” : “cell”, “st” : 1 }, “total” : 10 } |
count | db.product.aggregate({$group:{"_id":"$category", "total":{$sum:1}}}) | { “_id” : “laptop”, “total” : 3 } { “_id” : “cell”, “total” : 2 } |
sum & count | db.product.aggregate({$group:{"_id":"$category", "sum":{$sum:"$qty"}, "cnt":{$sum:1}}}) | { “_id” : “laptop”, “sum” : 80, “cnt” : 3 } { “_id” : “cell”, “sum” : 30, “cnt” : 2 } |
average | $avg | |
min | $min | |
max | $max |
Aggregation Pipeline:
Example | Return | Pipeline |
---|---|---|
db.product.aggregate({$match: {"store": 2}}, {$group: {"_id": "$category", "total": {$sum: "$qty"}}}, {$match: {"total": {$gt: 10}}}, {$limit: 2}, {$sort: {"total": 1}}) | { “_id” : “cell”, “total” : 20 } { “_id” : “laptop”, “total” : 70 } | $match ‐> $group ‐> $match ‐> $limit ‐> $sort |
Conditional Aggregation
Syntax | Example | Return |
---|---|---|
db.table({$group:{ ... }}, {$match:{ ... }}) | db.product.aggregate({$group:{"_id":"$category", "total":{$sum:"$qty"}}}, {$match:{"total":{$gt:50}}}) | { “_id” : “laptop”, “total” : 80 } |
Projection in Aggregation
Example | Return | Explanation |
---|---|---|
db.product.aggregate({$group:{"_id":null, "max":{$max:"$qty"}}}) | { “_id” : null, “max” : 45 } | Getting global max |
db.product.aggregate({$group:{"_id": null, "max":{$max: "$qty"}}}, {$project: {"_id": 0}}) | { “max” : 45 } | Remove “_id” from result |
Index
Syntax | Example | Explanation |
---|---|---|
db.table.getIndexes() | db.users.getIndexes() | Retrieve available indexes on users |
db.table.createIndex({ … :1}) | db.users.createIndes({"score":1}) | Create an index on “score”, with indx entries sorted by “score”, ascending |
db.table.createIndex({ … :1}, {unique:true}) | db.users.createIndex({"ssn":1}, {unique:true}) | Create a unique index of “ssn”, ascending |
db.table.dropIndex( … ) | db.users.dropIndex("ssn") | Drop the index of “ssn” |
Note: Unique field can take null values.
Index is useful in searching and sorting.
Query Plan
Example | Explanation |
---|---|
db.users.explain().find({"score": {$gt: 30}}) | Retrieve the query plan of the query in MongoDB |
Sharding in MongoDB
- Distribute documents/records in a large collection/table over multiple machines
- User can specify a sharding key – i.e., a field in a document
- Support sharding by key range or hashing
Writing JavaScript
Mongo shell supports Javascripting.
E.g.
> var cursor = db.users.find();
while ( cursor.hasNext() ) {
printjson( cursor.next() );
}
> db.users.find().forEach( function (user) {printjson (user);} );
Other Useful Methods
• db.person.findOne()
– Find a single document
• db.person.deleteOne()
– Remove a single document
• db.person.explain().find({age: {$gt: 20}})
– Explain query execution plan