Creating Documents in MongoDB
Creating Documents in MongoDB
In MongoDB, documents are the basic unit of data storage, similar to a row in a relational database. A document is a JSON-like object (stored as BSON in MongoDB) that consists of key-value pairs. You can create and insert documents into a collection, which is a group of related documents within a database.
Steps to Create a Document in MongoDB
Select a Database: First, switch to the database where you want to create the document. If the database doesn’t exist, MongoDB will create it automatically when you insert a document into a collection.
use myDatabase
Choose or Create a Collection: MongoDB collections are like tables in relational databases. You can insert a document into an existing collection, or if the collection doesn’t exist, MongoDB will create it on the fly when you insert a document.
Insert a Document: You can insert documents using the
insertOne()
,insertMany()
, or other methods, depending on how many documents you want to create.
Methods for Creating Documents
1. insertOne(): Insert a Single Document
This method allows you to insert a single document into a collection.
db.collection.insertOne(document)
collection
: The name of the collection where you want to insert the document.document
: The document to be inserted.
Example:
db.users.insertOne({
name: "John Doe",
age: 28,
email: "johndoe@example.com",
created_at: new Date()
})
This creates a new user document in the users
collection with fields like name
, age
, email
, and created_at
. If the users
collection does not already exist, MongoDB will create it.
2. insertMany(): Insert Multiple Documents
To insert multiple documents at once, use the insertMany()
method.
db.collection.insertMany([document1, document2, ...])
Example:
db.products.insertMany([
{ name: "Laptop", price: 899.99, in_stock: true },
{ name: "Smartphone", price: 699.99, in_stock: false }
])
This inserts two documents into the products
collection, representing a laptop and a smartphone.
Document Structure
MongoDB documents are made up of key-value pairs. Each key is a string, and the value can be any valid BSON data type, such as:
- String: "John Doe"
- Number: 28
- Boolean: true/false
- Date:
new Date()
(JavaScript's date object) - Array: [88, 92, 79] (a list of values)
- Object (embedded document):
{ city: "New York", state: "NY" }
- ObjectId: A unique 12-byte identifier, often used in the
_id
field to uniquely identify each document.
Here’s an example of a more complex document with various data types:
db.orders.insertOne({
customer: {
name: "Alice Smith",
email: "alice@example.com"
},
items: [
{ product: "Laptop", quantity: 1, price: 899.99 },
{ product: "Mouse", quantity: 2, price: 19.99 }
],
order_date: new Date(),
status: "shipped"
})
Auto-generated _id
Field
When inserting a document, if you do not explicitly provide an _id
field, MongoDB will automatically generate one. The _id
field is a unique identifier for each document in a collection.
{
_id: ObjectId("5f47df78bdbbfcf7b6a9e0d1"),
name: "John Doe",
age: 28,
email: "johndoe@example.com"
}
The _id
is usually of the ObjectId data type, but you can also manually assign a different value (e.g., string, integer) to the _id
field if needed.
Example:
db.customers.insertOne({
_id: "customer123",
name: "Charlie Brown",
email: "charlie@example.com"
})
In this case, the _id
is manually set to "customer123"
.
Upserting Documents
MongoDB supports an "upsert" operation, which is a combination of "update" and "insert". If a document matching the query exists, it will be updated; if not, a new document will be created.
Example of upsert:
db.users.updateOne(
{ email: "johndoe@example.com" }, // Query
{ $set: { name: "John Doe", age: 28 } }, // Update
{ upsert: true } // Upsert option
)
If no document with email: "johndoe@example.com"
exists, MongoDB will insert a new document with the specified values.
Insert Performance Considerations
- Bulk Inserts: Using
insertMany()
can improve performance when inserting multiple documents, as it reduces the number of write operations. - Write Concerns: MongoDB allows you to specify the level of acknowledgment from the database when inserting a document. For example, you can ensure the write is acknowledged by the majority of the replica set members for greater data safety.