Inserting Documents
Detailed explanation of inserting single and multiple documents into a collection with various data types.
Inserting a Single Document in MongoDB
Introduction
This section explains how to insert a single document into a MongoDB collection using the insertOne()
method. We'll cover the structure of a document, the syntax of insertOne()
, and the structure of the return value.
Understanding Documents in MongoDB
In MongoDB, data is stored in documents. A document is a set of field-value pairs. Documents are analogous to rows in relational database tables, but with the flexibility of schemaless data. Documents are stored in collections.
Structure of a Document
Documents are JSON-like structures (BSON – Binary JSON) consisting of fields and values. A field can hold different data types, including:
- String
- Number (Integer, Double, Decimal)
- Boolean
- Date
- Array
- Embedded Document (nested document)
- ObjectId (a unique identifier)
Example of a document:
{
"name": "John Doe",
"age": 30,
"city": "New York",
"is_active": true,
"hobbies": ["reading", "hiking", "coding"],
"address": {
"street": "123 Main St",
"zip": "10001"
}
}
Using the insertOne()
Method
The insertOne()
method is used to insert a single document into a collection. The syntax is as follows:
db.collectionName.insertOne(document, options)
db
: Refers to the current database.collectionName
: The name of the collection where you want to insert the document.document
: The document to insert. This is a JSON-like object.options
: (Optional) An object specifying additional options for the insertion. Common options includewriteConcern
andbypassDocumentValidation
. We won't cover options in detail in this basic guide.
Example 1: Inserting a Simple Document
Let's insert a simple document into a collection named "users":
db.users.insertOne(
{
"name": "Alice Smith",
"age": 25,
"city": "London"
}
)
Example 2: Inserting a Document with an Array
This example shows how to insert a document with an array field:
db.products.insertOne(
{
"name": "Laptop",
"price": 1200,
"tags": ["electronics", "computer", "portable"]
}
)
Example 3: Inserting a Document with a Nested Document
This demonstrates inserting a document containing another document (embedded document):
db.customers.insertOne(
{
"name": "Bob Johnson",
"email": "bob.johnson@example.com",
"address": {
"street": "456 Oak Ave",
"city": "Los Angeles",
"zip": "90001"
}
}
)
Example 4: Relying on MongoDB to automatically generate the _id field.
If you do not specify an _id
field in your document, MongoDB will automatically generate a unique ObjectId
for it. The _id
field serves as the primary key for the document. It is highly recommended to let MongoDB handle the _id
generation.
db.books.insertOne(
{
"title": "The Hitchhiker's Guide to the Galaxy",
"author": "Douglas Adams",
"pages": 224
}
)
The Return Value of insertOne()
The insertOne()
method returns an object containing information about the insertion operation. The most important property is acknowledged
and insertedId
.
{
"acknowledged" : true,
"insertedId" : ObjectId("654398a79514d6e28b791e6f")
}
acknowledged
: A boolean value indicating whether the write operation was acknowledged by the server. It's usuallytrue
.insertedId
: TheObjectId
of the inserted document. This is how you can uniquely identify the document you just inserted. If you specified your own_id
field in the document, this value will reflect that.
Example:
let result = db.users.insertOne({name: "Jane Doe", age: 28});
console.log(result.acknowledged); // Output: true
console.log(result.insertedId); // Output: ObjectId("654398a79514d6e28b791e6f") (or similar)
Important Considerations
- Data Type Consistency: While MongoDB is schemaless, it's good practice to maintain consistency in data types within a collection for ease of querying and analysis. For instance, if one document has the "age" field as a number, subsequent documents should also store "age" as a number.
- Error Handling: In a production environment, you should always wrap your
insertOne()
calls in a try-catch block to handle potential errors, such as network issues or write conflicts.