1. What is MongoDB?
MongoDB is a document-oriented database. It stores data in documents that look like JSON. It uses collections to group documents.
Full lesson: Mongodb intro
45 questions about MongoDB with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
MongoDB is a document-oriented database. It stores data in documents that look like JSON. It uses collections to group documents.
Full lesson: Mongodb intro
A collection is a group of documents inside a database. It is like a table in a relational database.
Full lesson: Mongodb intro
A document is one data record in a collection. It is made of key-value pairs and stored in BSON format. It is like a row in a relational database.
Full lesson: Mongodb intro
Use the insertOne method on a collection. Pass the document as an object. MongoDB adds an _id field if you do not give one.
db.users.insertOne({ name: "Tom", age: 30 })
Full lesson: Mongodb insert
Call find with no arguments. It returns all documents in the collection.
db.myCollection.find()
Full lesson: Mongodb query
Pass a query object to the find method. MongoDB returns only the documents that match. This example finds users older than 25.
db.myCollection.find({ age: { $gt: 25 } })
Full lesson: Mongodb query
Use the updateOne method with a filter and an update operator. The $set operator changes a field value.
db.users.updateOne({ name: "Tom" }, { $set: { age: 31 } })
Full lesson: Mongodb update
Use the deleteOne method with a filter. MongoDB removes the first document that matches the filter.
db.users.deleteOne({ name: "Tom" })
Full lesson: Mongodb remove
The MongoDB Shell is an interactive command line tool. It uses JavaScript. You can run commands and scripts in it.
Full lesson: Mongodb shell
An index is a special data structure that speeds up queries. Without an index, MongoDB scans every document in the collection.
db.collection.createIndex({ age: 1 })
Full lesson: Mongodb indexing
An ObjectId is a 12-byte BSON value. It holds a timestamp, a machine code, a process ID, and a random number. MongoDB uses it as the default _id value.
newObjectId = ObjectId()
Full lesson: Mongodb objectid
Add the sort method after find. Use 1 for ascending order and -1 for descending order.
db.users.find().sort({ age: -1 })
Full lesson: Mongodb sort
Use the $type operator in the query. You can give a type name or a numeric code. MongoDB returns documents whose field has that type.
db.collection.find({ age: { $type: "int" } })
Full lesson: Mongodb operators type
Each index needs storage space. MongoDB must also update the index on every insert, update, and delete. Too many indexes add overhead to writes.
Full lesson: Mongodb indexing limitations
MongoDB creates an index entry for each array value. A large array makes the index grow fast. Check the array size before you add the index.
db.users.createIndex({ tags: 1 })
Full lesson: Mongodb advanced indexing
NoSQL means Not Only SQL. It is a database movement for data that does not fit well in relational tables.
Full lesson: Nosql
Download the MongoDB Community Server package from the official website. Run the installer and follow the steps.
Full lesson: Mongodb window install
Open a terminal and type mongosh. The shell connects to the default host and port.
mongosh
Full lesson: Mongodb shell
Use the db.createUser() method in the admin database. Provide a user name, a password, and roles.
db.createUser({ user: "admin", pwd: "pass", roles: ["root"] })
Full lesson: Mongodb user
Use the insertMany() method. Pass an array of documents to the method.
db.users.insertMany([{ name: "Alice" }, { name: "Bob" }])
Full lesson: Mongodb insert
Use the updateMany() method. It updates all documents that match the filter.
db.users.updateMany({ age: { $lt: 30 } }, { $set: { status: "young" } })
Full lesson: Mongodb update
Use the deleteMany() method. It deletes all documents that match the filter.
db.users.deleteMany({ status: "inactive" })
Full lesson: Mongodb remove
Use the createIndex() method on the array field. MongoDB creates a separate index entry for each array element.
db.users.createIndex({ tags: 1 })
Full lesson: Mongodb advanced indexing
GridFS stores files that are larger than 16 MB. It splits a file into small chunks and stores the chunks in two collections.
Full lesson: Mongodb gridfs
Use the MongoDB PHP driver. Create a MongoClient object to connect to the database.
<?php
$m = new MongoClient();
$db = $m->test;
?>
Full lesson: Mongodb php
Add the MongoDB Java driver jar to your classpath. Use the MongoClient class to connect.
MongoClient mongoClient = new MongoClient("localhost", 27017);
Full lesson: Mongodb java
You add extra write overhead and use storage space for no benefit. Do not create an index on a field that you rarely query.
Full lesson: Mongodb indexing limitations
You expect the index to speed up the query. MongoDB cannot use an index for regular expressions and operators such as $nin and $not.
Full lesson: Mongodb indexing limitations
You forget that 1 means ascending order and -1 means descending order. Use the correct number for the order you want.
db.users.find().sort({ age: 1 })
Full lesson: Mongodb sort
You try to install a 32-bit version on a modern system. The latest versions do not have 32-bit installation files.
Full lesson: Mongodb window install
Use the package manager for your Linux distribution. Import the MongoDB public key and add the repository first. Then install the mongodb-org package.
sudo apt-get install -y mongodb-org
Full lesson: Mongodb linux install
Use Homebrew to install MongoDB on macOS. Run the brew tap command first. Then run the brew install command.
brew tap mongodb/brew
brew install mongodb-community
Full lesson: Mongodb osx install
updateOne changes fields with update operators. replaceOne replaces the whole document with a new document. Use replaceOne when you want a full replacement.
db.users.replaceOne({ name: "Alice" }, { name: "Alice", age: 30 })
Full lesson: Mongodb update
The $set operator changes the value of a field. It adds the field if the field does not exist. Other fields stay the same.
db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } })
Full lesson: Mongodb update
The upsert option creates a new document when no document matches the filter. Set upsert to true in the options object. The update then inserts a document.
db.users.updateOne({ name: "Bob" }, { $set: { age: 20 } }, { upsert: true })
Full lesson: Mongodb update
A compound index includes more than one field. It can speed up queries that filter on those fields. The field order in the index matters.
db.users.createIndex({ name: 1, age: -1 })
Full lesson: Mongodb advanced indexing
A unique index stops duplicate values in a field. MongoDB rejects an insert or update that makes a duplicate value. Create it with the unique option.
db.users.createIndex({ email: 1 }, { unique: true })
Full lesson: Mongodb indexing
A text index supports text search on string fields. Create it with the text value. Then use the $text operator in a query.
db.articles.createIndex({ body: "text" })
db.articles.find({ $text: { $search: "mongodb" } })
Full lesson: Mongodb advanced indexing
A covered query reads all data from the index. The query does not read the documents. The index must include all fields in the filter and the projection.
db.users.find({ name: "Alice" }, { _id: 0, name: 1 }).hint({ name: 1 })
Full lesson: Mongodb advanced indexing
The findOneAndUpdate method updates one document and returns it. It returns the document before or after the update. Use the returnDocument option to choose.
db.users.findOneAndUpdate({ name: "Alice" }, { $set: { age: 27 } }, { returnDocument: "after" })
Full lesson: Mongodb update
An empty filter matches the first document in the collection. The update changes a document that you did not choose. Always use a clear filter for updateOne.
db.users.updateOne({ _id: ObjectId("...") }, { $set: { age: 26 } })
Full lesson: Mongodb update
An empty filter in deleteMany removes all documents. The data is gone and you cannot undo the delete. Use a clear filter or deleteOne for safety.
db.users.deleteMany({ status: "inactive" })
Full lesson: Mongodb remove
A plain field name replaces the whole nested object. Use dot notation to change one nested field. The dot notation keeps the other nested fields.
db.users.updateOne({ name: "Alice" }, { $set: { "address.city": "Paris" } })
Full lesson: Mongodb update
The index creation fails if duplicate values exist. Clean the duplicate data first. Then create the unique index.
db.users.createIndex({ email: 1 }, { unique: true })
Full lesson: Mongodb indexing limitations
A compound index has a limit on the number of fields. Too many fields make the index large and slow to update. Keep the index small and match your queries.
db.users.createIndex({ a: 1, b: 1, c: 1 })
Full lesson: Mongodb indexing limitations