Skip to main content

MongoDB $push Operator

Arrays are a powerful feature in MongoDB that allow you to store multiple values within a single field. The $push operator is one of the most commonly used update operators for manipulating arrays in MongoDB documents.

Introduction to the $push Operator

The $push operator appends a specified value to an array. If the field doesn't exist, $push creates the array field with the specified value as its element. If the field is not an array, the operation will fail.

Think of $push as adding a new item to a shopping cart or adding a new comment to a post - it's the way you expand array data in MongoDB.

Basic Syntax

js
db.collection.update(
<query>,
{ $push: { <field1>: <value1>, ... } }
)

Let's break down the components:

  • <query>: The selection criteria for the document to update
  • <field1>: The array field to update
  • <value1>: The value to add to the array

Simple Examples

Example 1: Adding an Element to an Array

Consider a collection of blog posts where we want to add a new tag to a post:

js
// Original document
{
_id: ObjectId("5f8d5a7c9d3b2e1234567890"),
title: "Introduction to MongoDB",
tags: ["database", "nosql"]
}

// Add a new tag
db.posts.updateOne(
{ _id: ObjectId("5f8d5a7c9d3b2e1234567890") },
{ $push: { tags: "mongodb" } }
)

// Result
{
_id: ObjectId("5f8d5a7c9d3b2e1234567890"),
title: "Introduction to MongoDB",
tags: ["database", "nosql", "mongodb"]
}

Example 2: Creating a New Array Field

If the field doesn't exist, $push creates it:

js
// Original document
{
_id: ObjectId("5f8d5a7c9d3b2e1234567891"),
title: "MongoDB Aggregation",
content: "MongoDB aggregation framework..."
}

// Add a new comments array
db.posts.updateOne(
{ _id: ObjectId("5f8d5a7c9d3b2e1234567891") },
{ $push: { comments: "Great article!" } }
)

// Result
{
_id: ObjectId("5f8d5a7c9d3b2e1234567891"),
title: "MongoDB Aggregation",
content: "MongoDB aggregation framework...",
comments: ["Great article!"]
}

Advanced pushFeatureswithpush Features with each, slice,slice, sort, and $position

The $push operator becomes even more powerful when combined with modifiers:

Using $each to Add Multiple Values

The $each modifier allows you to add multiple values to an array:

js
db.posts.updateOne(
{ _id: ObjectId("5f8d5a7c9d3b2e1234567890") },
{
$push: {
tags: {
$each: ["tutorial", "beginner", "guide"]
}
}
}
)

// Result
{
_id: ObjectId("5f8d5a7c9d3b2e1234567890"),
title: "Introduction to MongoDB",
tags: ["database", "nosql", "mongodb", "tutorial", "beginner", "guide"]
}

Using $slice to Limit Array Size

The $slice modifier limits the size of the array after the $push operation:

js
// Keep only the last 5 elements
db.posts.updateOne(
{ _id: ObjectId("5f8d5a7c9d3b2e1234567890") },
{
$push: {
tags: {
$each: ["new-tag"],
$slice: -5 // Keep only the last 5 elements
}
}
}
)

// Result (assuming we had 6+ elements before)
{
_id: ObjectId("5f8d5a7c9d3b2e1234567890"),
title: "Introduction to MongoDB",
tags: ["mongodb", "tutorial", "beginner", "guide", "new-tag"]
}

Using $sort to Order Elements

The $sort modifier sorts the elements of the array:

js
db.inventory.updateOne(
{ _id: "stock_item" },
{
$push: {
prices: {
$each: [{ price: 10.99, date: ISODate("2022-01-01") }],
$sort: { price: 1 } // Sort prices in ascending order
}
}
}
)

Using $position to Insert at a Specific Position

The $position modifier specifies the position in the array where elements should be inserted:

js
db.posts.updateOne(
{ _id: ObjectId("5f8d5a7c9d3b2e1234567890") },
{
$push: {
tags: {
$each: ["important"],
$position: 0 // Insert at the beginning of the array
}
}
}
)

// Result
{
_id: ObjectId("5f8d5a7c9d3b2e1234567890"),
title: "Introduction to MongoDB",
tags: ["important", "mongodb", "tutorial", "beginner", "guide"]
}

Practical Examples

Example 1: Managing a User's Shopping Cart

Imagine you have an e-commerce application. When users add items to their cart, you can use $push:

js
// Add an item to a user's cart
db.users.updateOne(
{ _id: userId },
{
$push: {
cart: {
productId: ObjectId("5f8d5a7c9d3b2e1234567892"),
name: "Wireless Headphones",
price: 99.99,
quantity: 1,
addedAt: new Date()
}
}
}
)

Example 2: Adding Comments to a Blog Post with a Limit

For a blog post with comments, you might want to keep only the most recent comments visible:

js
// Add a new comment and keep only the 10 most recent
db.posts.updateOne(
{ _id: postId },
{
$push: {
comments: {
$each: [{
user: "John",
text: "Great tutorial!",
createdAt: new Date()
}],
$sort: { createdAt: -1 }, // Sort by newest first
$slice: 10 // Keep only 10 most recent
}
}
}
)

Example 3: Tracking User Activity

For user activity logs, you might append new activities and keep only recent ones:

js
db.users.updateOne(
{ username: "sarah_dev" },
{
$push: {
activityLog: {
$each: [{
action: "login",
timestamp: new Date(),
ipAddress: "192.168.1.1"
}],
$slice: -100 // Keep only the 100 most recent activities
}
}
}
)

Common Pitfalls and Best Practices

Pitfalls to Avoid:

  1. Unbounded arrays: Without $slice, arrays can grow indefinitely and impact performance.

  2. Duplicates: By default, $push will add duplicate values. If you want unique values, consider using $addToSet instead.

  3. Non-array fields: Using $push on a non-array field will result in an error.

Best Practices:

  1. Limit array sizes: Use $slice for arrays that can grow large over time.

  2. Index array fields: If you query on array elements, create appropriate indexes.

  3. Consider embedding limits: For heavily nested documents, be mindful of MongoDB's 16MB document size limit.

When to Use $push vs Other Operators

  • Use $push when you want to append items to an array, potentially with duplicates.
  • Use $addToSet when you want to ensure no duplicates in the array.
  • Use $pull when you want to remove items from an array.
  • Use $pop when you want to remove items from the beginning or end of an array.

Summary

The $push operator is an essential tool for working with arrays in MongoDB:

  • It adds elements to arrays within documents
  • It can create new array fields if they don't exist
  • With modifiers ($each, $slice, $sort, $position), it offers powerful array manipulation options
  • It's ideal for use cases like activity logs, comments, tags, and shopping carts

By mastering the $push operator and its modifiers, you can efficiently implement many common data patterns in MongoDB applications.

Additional Resources

Practice Exercises

  1. Create a todo list application where you can:

    • Add new tasks to a user's task list
    • Keep only the 20 most recent tasks
    • Sort tasks by priority
  2. Implement a social media post model where:

    • Users can add comments
    • Comments are sorted by date
    • Only the 50 most recent comments are kept
    • New comments with high engagement can be inserted at the top
  3. Design a notification system that:

    • Adds new notifications to a user's notification array
    • Limits the array to the 100 newest notifications
    • Sorts notifications by importance and date

Happy coding!



If you spot any mistakes on this website, please let me know at feedback@compilenrun.com. I’d greatly appreciate your feedback! :)