Sling Academy
Home/MongoDB/Object data type in MongoDB: Tutorial & Examples

Object data type in MongoDB: Tutorial & Examples

Last updated: February 02, 2024

Introduction

MongoDB, the popular NoSQL database, uses flexible schema allowing developers to store different types of data. One of the main data structures in MongoDB is the object data type, which allows for storing documents in a nested, hierarchical format. This tutorial aims to provide an understanding of the object data type and how to work with it in MongoDB through various examples.

Understanding Object Data Type in MongoDB

In MongoDB, the object data type refers to a structure representing a document or a subdocument. This data type closely resembles a JSON object in structure but is stored as BSON (Binary JSON). It is a collection of field-value pairs where the values can be various data types, including another object, arrays, and more.

  • Basic Object: Simple key-value pairs.
  • Nested Object: An Object containing another object.

Example 1: Basic Object

{
  "name": "John Doe",
  "age": 30,
  "email": "[email protected]"
}

This simple document can be directly inserted into a MongoDB collection.

Example 2: Nested Object

{
  "name": "John Doe",
  "contact": {
    "email": "[email protected]",
    "phone": "123-456-7890"
  }
}

The contact field itself is an object, demonstrating a nested structure.

Working with Objects

To work with objects, we use MongoDB’s CRUD operations: create, read, update, and delete.

Creating and Inserting Objects

To insert a document into a collection, we use the insertOne or insertMany method.

Example 3: Inserting a Document

db.collection.insertOne({
  "firstname": "Jane",
  "lastname": "Doe",
  "contact": {
    "email": "[email protected]",
    "phone": "987-654-3210"
  }
});

Read operations can retrieve documents using find method.

Example 4: Reading a Document

db.collection.find({ "lastname": "Doe" });

This query will return all documents with the lastname “Doe”.

Updating Objects

Update operations modify existing documents. The updateOne method changes a single document based on the criteria passed.

Example 5: Updating a Document

db.collection.updateOne(
  { "lastname": "Doe" },
  {
    $set: { "contact.email": "[email protected]" }
  }
);

The $set operator is used to update the email within the nested contact object for documents with the lastname “Doe”.

Deleting Objects

Delete operations remove documents from the collection. The deleteOne method deletes a single document that matches the criteria.

Example 6: Deleting a Document

db.collection.deleteOne({ 
  "firstname": "Jane" 
});

This will delete a document where the firstname is “Jane”.

Advanced Operations

MongoDB provides advanced features such as aggregation and indexing that can make working with objects more efficient.

Using Aggregation on Objects

Aggregation operations process multiple documents and return computed results.

Example 7: Aggregation with Group

db.collection.aggregate([
  { $group: {
    _id: "$lastname",
    total: { $sum: 1 }
  } }
]);

This operation groups documents based on the lastname field and counts how many documents belong to each group.

Indexing Object Fields

To speed up query performance, especially on fields within nested objects, it’s crucial to create indexes.

Example 8: Creating an Index

db.collection.createIndex({ 
  "contact.email": 1 
});

This will create an ascending index on the email field inside the contact nested object.

Using the dot notation in Queries

To access fields within nested objects, the dot notation is used in queries, updates, and field projections.

Example 9: Query using Dot Notation

db.collection.find({ 
  "contact.email": "[email protected]" 
});

This query will find documents where the nested email field matches a specific value.

Example 10: Update using Dot Notation

db.collection.updateMany(
  { "contact.email": { $exists: true } },
  { $set: { "contact.type": "personal" } }
);

This will add a new field type inside the contact object of all documents that have an email field.

Best Practices

When using nested objects:

  • Avoid deep nesting as it can complicate queries and impact performance.
  • Consider data usage patterns to determine if nested objects are the best choice or if referencing another document is more appropriate.
  • Use meaningful field names to make the data structure self-describing.

Conclusion

Understanding MongoDB’s object data type and employing effective schema design is fundamental to harnessing the full power of MongoDB. Proper use of nesting and indexing can lead to more efficient data retrieval and management.

Next Article: Undefined and Null data types in MongoDB (with examples)

Previous Article: Array data type in MongoDB: A practical guide (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)