Chapter 1 Introduction
Designed to Scale
Rich with Features:
MongoDB is a general-purpose database,so aside from creating,reading,updating,and deleting data,it provides most of the featuress you would expect from a database management system and many others that set it part.These include:
- Indexing
- Aggregation
- Special collection and index types
- File storage
Without Sacrificing Speed
Performance is a driving objective for MongoDB, and has shaped much of its design.
Chapter 2 Getting Started
The basic concepts of MongoDB:
- A document is the basic unit of data for MongoDB and is roughly equivalent to a row in a relational database management system(but much more expressive)
- Similarly,a collection can be thought of as a table with a dynamic schema.
- A single instance of MongoDB can host multiple independent databases,each of which contains its own collections.
- Every document has a special key,'_id',that is unique within a collection.
- MongoDB is distributed with a simple but powerful tool called the mongo shell.
Documents
an orderes set of keys with associated values.
The keys in a document are strings.Any UTF-8 character is allowed in a key,with a few notable exceptions:
- Keys must not contain the character \0 (the null character).This character is used to signify the end of a key.
- The .?and $??characters have some special properties and should be used only in certain circumstances
MongoDB is type-sensitive and case-sensitive.
A final important thing to note is that documents in MongoDB cannot contain duplicate keys.
Collections
A collection is a group of documents.If a document is the MongoDB analog of a row in a relational database, then a collection can be tohought of as the analog to a table.
Dynamic Schemas
Collections have dynamic schemas. This means that the documents within a single collection can have any number of different "shape".
Why should we use more than one collection?
- Keeping different kinds of documents in the same collection can be a nightmare for developers and admins.
- It's much faster to get a list of collections than to extract a list of the types of documents in a collection.
- Grouping documents of the same kind together in the same collection allows for data locality.
- We begin to impose some structure on our documents when we create indexes.
Naming?
A collection is identified by its name. Collection names can be any UTF-8 string, with a few restrictions:
- The empty string (" ") is not a valid collection name.
- Collection names may not contain the character \0 (the null character), because this delineates the end of a collection name.
- You should not create any collections with names that start with system. a prefix reserved for internal collections. The system.users collection contains the database's users, and the system.namespaces collection contains information about all of the database's collections.
- User-created collections should not contain the reserved character $ in their names.
Subcollections
one convention for organizing collections is to use namespaced subcollections separated by the .? character.?
- GridFS a protocol for storing large files, uses subcollections to store file metadata separately from content chunks.
- Most drivers provide some syntactic sugar for accessing a subcollection of a given collection.
Subcollections are a good way to organize data in MongoDB for many use case.
Databases
In addition to grouping documents by collection,MongoDB groups collections into databases.A single instance of MongoDB can host several databases, each grouping together zero or more collections.
Database name can be any UTF-8 string with the following restrictions:
- The empty string (" ") is not a valid database name.
- A database name cannot contain any of these characters:/,\,.,",*,<,>,:,|,?,$,or \0(the null character). Basically,stick with alphanumeric ASCII.
- Database name are case-insensitive
- Database names are limited to a maximum of 64 bytes.
The are also some reserved database names, which you can access but which have special semantics s.These are as follows:
Getting and Starting MongoDB
>? > show dbs admin ? ? ? 0.000GB categories ?0.000GB config ? ? ?0.000GB garden ? ? ?0.000GB local ? ? ? 0.000GB products ? ?0.000GB test ? ? ? ?0.000GB > x = 200 200 > x / 5 40 > Math.sin(Math.PI / 2); 1 > new Date("201009/1/1"); ISODate("201008-12-31T16:00:00Z") > "Hello, World!".replace("World","MongoDB"); Hello, MongoDB! > function factorial(n){ ... if (n <= 1) return 1; ... return n * factorial(n-1); ... } > factorial(5); 120 >?
A MongoDB Client
> db test > use video switched to db video > db video > db.movies video.movies >?
Basic Operations with the Shell
We can use the four basic operations,create,read,update,and delete (CRUD),to manipulate and view data in the shell.
Create
The insertOne function adds a document to a collection.
>? > movie = {"title" : "Star Wars: Episode IV - A New Hope", "director" : "George Lucas", "year" : 1977} { ? ? ? ? "title" : "Star Wars: Episode IV - A New Hope", ? ? ? ? "director" : "George Lucas", ? ? ? ? "year" : 1977 } > db.movies.insertOne(movie) { ? ? ? ? "acknowledged" : true, ? ? ? ? "insertedId" : ObjectId("624a64421430d4af015414a0") } > db.movies.find().pretty() { ? ? ? ? "_id" : ObjectId("624a64421430d4af015414a0"), ? ? ? ? "title" : "Star Wars: Episode IV - A New Hope", ? ? ? ? "director" : "George Lucas", ? ? ? ? "year" : 1977 } >?
Read
find and findOne can be used to query a collection.If we just want to use one document from a collection,we can use findOne:
Update
If we would like to modify our post,we can use updateOne.updateOne takes two parameters: the first is the criteria to find which document to update, and the second is a document describing the updates to make.
>? > db.movies.updateOne({title: "Star Wars: Episode IV - A New Hope"}, ... {$set:{reviews: []}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } > db.movies.find().pretty() { ? ? ? ? "_id" : ObjectId("624a64421430d4af015414a0"), ? ? ? ? "title" : "Star Wars: Episode IV - A New Hope", ? ? ? ? "director" : "George Lucas", ? ? ? ? "year" : 1977, ? ? ? ? "reviews" : [ ] } >?
Delete?
>? > db.movies.find().pretty() { ? ? ? ? "_id" : ObjectId("624a64421430d4af015414a0"), ? ? ? ? "title" : "Star Wars: Episode IV - A New Hope", ? ? ? ? "director" : "George Lucas", ? ? ? ? "year" : 1977, ? ? ? ? "reviews" : [ ] } > db.movies.deleteOne({title: "Star Wars: Episode IV - A New Hope"}) { "acknowledged" : true, "deletedCount" : 1 } > db.movies.find().pretty() >
Data Types
Basic Data Types
Document in MongoDB can be thought of as "JSON-Like" in that they are conceptually similar to objects in JavaScript.JSON is a simple representation of data.
The most common types are:
- Null The null type can be used to represent both a null value and a nonexistent field.
- Boolean? There is a boolean type,which can be used for the values true and false.
- Number The shell defaults to using 64-bit floating-point numbers.Thus, these numbers both look "normal" in the shell.
- For integers,use the NumberInt or NumberLong classes,which represent 4-byte or 8-byte signed integers,respectively.
- String any string of UTF-8 characters can be represented using the string type.
- Date MongoDB stores dates as 64-bit integers representing milliseconds since the Unix epoch. {"x": new Date()}
- Regular expression Queries can use regular expressions using JavaScript's regular expression syntax.
- Array Set or lists of values can be represented as arrays.
- Embedded document Documents can contain entire documents embedded as values in a parent documents
- Object ID An object ID is 12-byte ID for documents.
There are also a few less common types that you may need, including:
Dates
Arrays
Arrays are values that can be used interchangeably for both? ordered operations and unordered operations.
Embedded Documents
A document can be used as the value for a key. This called an embedded document.
_id and Objectlds
Every document stored in MongoDB must have an "_id" key.
Objectlds
ObjectId is the default type for "_id".
Using the MongoDB Shell
[maxwell@DBAMAXWELL mongodb_learn]$ mongo --nodb MongoDB shell version v4.4.13 Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see ? ? ? ? https://docs.mongodb.com/ Questions? Try the MongoDB Developer Community Forums ? ? ? ? https://community.mongodb.com >?
Tips for using the Shell
>? > help ? ? ? ? db.help() ? ? ? ? ? ? ? ? ? ?help on db methods ? ? ? ? db.mycoll.help() ? ? ? ? ? ? help on collection methods ? ? ? ? sh.help() ? ? ? ? ? ? ? ? ? ?sharding helpers ? ? ? ? rs.help() ? ? ? ? ? ? ? ? ? ?replica set helpers ? ? ? ? help admin ? ? ? ? ? ? ? ? ? administrative help ? ? ? ? help connect ? ? ? ? ? ? ? ? connecting to a db help ? ? ? ? help keys ? ? ? ? ? ? ? ? ? ?key shortcuts ? ? ? ? help misc ? ? ? ? ? ? ? ? ? ?misc things to know ? ? ? ? help mr ? ? ? ? ? ? ? ? ? ? ?mapreduce
? ? ? ? show dbs ? ? ? ? ? ? ? ? ? ? show database names ? ? ? ? show collections ? ? ? ? ? ? show collections in current database ? ? ? ? show users ? ? ? ? ? ? ? ? ? show users in current database ? ? ? ? show profile ? ? ? ? ? ? ? ? show most recent system.profile entries with time >= 1ms ? ? ? ? show logs ? ? ? ? ? ? ? ? ? ?show the accessible logger names ? ? ? ? show log [name] ? ? ? ? ? ? ?prints out the last segment of log in memory, 'global' is default ? ? ? ? use <db_name> ? ? ? ? ? ? ? ?set current database ? ? ? ? db.mycoll.find() ? ? ? ? ? ? list objects in collection mycoll ? ? ? ? db.mycoll.find( { a : 1 } ) ?list objects in mycoll where a == 1 ? ? ? ? it ? ? ? ? ? ? ? ? ? ? ? ? ? result of the last line evaluated; use to further iterate ? ? ? ? DBQuery.shellBatchSize = x ? set default number of items to display on shell ? ? ? ? exit ? ? ? ? ? ? ? ? ? ? ? ? quit the mongo shell >
Running Scripts with the Shell
In addition to using the shell interactively,you can also pass the shell JavaScript files to execute.
[maxwell@DBAMAXWELL mongodb_learn]$ mongo script1.js script2.js script3.js MongoDB shell version v4.4.13 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("2f9ef43e-f78b-4856-acde-a25b4157df63") } MongoDB server version: 4.4.13 loading file: script1.js I am script1.js loading file: script2.js I am script2.js loading file: script3.js I am script3.js [maxwell@DBAMAXWELL mongodb_learn]$?
You can also run scripts from within the interactive shell using the load function:
[maxwell@DBAMAXWELL mongodb_learn]$ mongo MongoDB shell version v4.4.13 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("43ae6f35-2959-425c-b62e-34e251c66733") } MongoDB server version: 4.4.13 Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see ? ? ? ? https://docs.mongodb.com/ Questions? Try the MongoDB Developer Community Forums ? ? ? ? https://community.mongodb.com --- The server generated these startup warnings when booting:? ? ? ? ? 2022-03-23T23:33:56.417+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted --- --- ? ? ? ? Enable MongoDB's free cloud-based monitoring service, which will then receive and display ? ? ? ? metrics about your deployment (disk utilization, CPU, operation statistics, etc).
? ? ? ? The monitoring data will be available on a MongoDB website with a unique URL accessible to you ? ? ? ? and anyone you share the URL with. MongoDB may use this information to make product ? ? ? ? improvements and to suggest MongoDB products and deployment options to you.
? ? ? ? To enable free monitoring, run the following command: db.enableFreeMonitoring() ? ? ? ? To permanently disable this reminder, run the following command: db.disableFreeMonitoring() --- > load("script1.js") I am script1.js true >?
If you load this script in the shell, connectTo is now defined.
[maxwell@DBAMAXWELL mongodb_learn]$ mongo --nodb MongoDB shell version v4.4.13 Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see ? ? ? ? https://docs.mongodb.com/ Questions? Try the MongoDB Developer Community Forums ? ? ? ? https://community.mongodb.com >? > typeof connectTo undefined > load('defineConnectTo.js') true > typeof connectTo function >?
You can use run to run command-line programs from the shell.You can pass arguments to the function as parameters:
[maxwell@DBAMAXWELL mongodb_learn]$ mongo --nodb MongoDB shell version v4.4.13 Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see ? ? ? ? https://docs.mongodb.com/ Questions? Try the MongoDB Developer Community Forums ? ? ? ? https://community.mongodb.com > typeof connectTo undefined > load('defineConnectTo.js') true > typeof connectTo function > run("ls","-l","/home/learning/mongodb_learn/") {"t":{"$date":"2022-04-04T11:05:52.300Z"},"s":"I", ?"c":"-", ? ? ? ?"id":22810, ? "ctx":"js","msg":"shell: Started program","attr":{"pid":"828945","argv":["/usr/bin/ls","-l","/home/learning/mongodb_learn/"]}} sh828945| total 16 sh828945| -rw-r--r-- 1 maxwell root 186 Apr ?4 19:00 defineConnectTo.js sh828945| -rwxrwxr-x 1 maxwell root ?26 Apr ?4 18:28 script1.js sh828945| -rwxrwxr-x 1 maxwell root ?26 Apr ?4 18:29 script2.js sh828945| -rwxrwxr-x 1 maxwell root ?26 Apr ?4 18:29 script3.js 0 >?
?Creating a .mongorc.js
If you have frequently loaded scripts,you might want to put them in your .mongorc.js file.This file is run whenever you start up the shell.
Customizing Your Prompt
The default shell prompt can be overridden by setting the prompt variable to either a string or a function.
prompt = function(){
? ? ? ? return (new Date())+"> ";
};
Another handy prompt might show the current database you're using:
prompt = function() {
? ? ? ? ?if (typeof db == 'undefined'){
? ? ? ? ? ? ?return '(nodb)> ';?
???????? }
? ? ? ? // Check the last db operation
? ? ? ? try {
? ? ? ? ? ? ?db.runCommand({getLastError:1});
????????}
? ? ? ? catch (e) {
? ? ? ? ? ? ? print(e);
? ? ? ? ?}
? ? ? ? ?return db+"> ";
};
Inconvenient Collection Names
> db.version function() { ? ? return this.serverBuildInfo().version; } > db.getCollection("version"); max.version > var collections = ["posts","comments","authors"]; > for (var i in collections) { ... print(db.blog[collections[i]]); ... } max.blog.posts max.blog.comments max.blog.authors >?
|