배열 업데이트하기: $push, $pull, $pop, $addToSet
학습자는 배열 업데이트 연산자의 전체 집합을 사용해 문서 내부의 배열을 원자적으로 수정합니다.
배열 업데이트하기: $push, $pull, $pop, $addToSet은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Array Update Operators Overview
MongoDB provides a rich set of array update operators that let you modify arrays inside documents atomically—without reading the document first, modifying it in application code, and writing it back. These operators are far more efficient and safe in concurrent environments than read-modify-write patterns. The main operators are: $push, $pull, $pop, and $addToSet.
Adding Elements With $push
$push appends one or more values to the end of an array. If the field does not exist, $push creates it as a new array containing the pushed value. $push allows duplicates—if you push the same value twice, it appears twice in the array. Use it when order and duplicates are acceptable, like append-only log arrays.
// Append a single tag
db.articles.updateOne(
{ _id: articleId },
{ $push: { tags: 'mongodb' } }
);
// Push creates the array if it doesn't exist
db.articles.updateOne(
{ _id: newId },
{ $push: { views: { date: new Date(), userId: 'u1' } } }
);
// If 'views' didn't exist, it's now [{ date: ..., userId: 'u1' }]$push With $each: Pushing Multiple Values
To push multiple values at once without multiple updateOne calls, combine $push with the $each modifier. This is more efficient and atomic. You can also combine $each with $position to insert at a specific index, $slice to cap the array length, or $sort to keep the array sorted after the push.
// Push multiple values atomically
db.articles.updateOne(
{ _id: articleId },
{ $push: { tags: { $each: ['nosql', 'database', 'tutorial'] } } }
);
// Push and keep only the 5 most recent (slice)
db.users.updateOne(
{ _id: userId },
{ $push: { recentViews: { $each: [newView], $slice: -5 } } } // keep last 5
);
// Push and sort by score descending
db.leaderboard.updateOne(
{ _id: gameId },
{ $push: { scores: { $each: [newEntry], $sort: { score: -1 } } } }
);Preventing Duplicates With $addToSet
$addToSet adds a value to an array only if it does not already exist. If the value is already in the array, the operation has no effect. This is the correct operator for maintaining a set of unique values, like a list of user tags, role names, or liked post IDs. Unlike $push, $addToSet guarantees no duplicates.
// Add tag only if not already present
db.articles.updateOne(
{ _id: articleId },
{ $addToSet: { tags: 'mongodb' } }
);
// If 'mongodb' is already in tags, nothing changes
// Add multiple unique values with $each
db.users.updateOne(
{ _id: userId },
{ $addToSet: { roles: { $each: ['editor', 'viewer'] } } }
);
// Only adds values not already in roles arrayRemoving Elements With $pull
$pull removes all array elements that match a specified condition. Unlike $pop (which removes by position), $pull removes by value or condition. You can pull by exact value, by a query expression, or by a complex condition using $elemMatch-style sub-document matching.
// Remove all elements equal to 'draft' from tags
db.articles.updateOne(
{ _id: articleId },
{ $pull: { tags: 'draft' } }
);
// Remove all scores below 50
db.results.updateOne(
{ _id: studentId },
{ $pull: { scores: { $lt: 50 } } }
);
// Pull a specific sub-document from an array
db.users.updateOne(
{ _id: userId },
{ $pull: { addresses: { type: 'work' } } } // remove all work addresses
);Removing Multiple Matching Elements
$pull removes all matching elements, not just the first one. If your array has duplicates and you want to remove all copies, $pull handles this in one operation. For removing from multiple documents, combine with updateMany() to pull from every matching document in the collection.
// Remove the role 'temp' from ALL users at once
db.users.updateMany(
{},
{ $pull: { roles: 'temp' } }
);
// Pull sub-documents matching a condition
db.posts.updateMany(
{},
{ $pull: { comments: { isSpam: true } } } // remove spam from all posts
);Removing From Position With $pop
$pop removes the first or last element of an array based on position. Pass 1 to remove the last element (like a stack pop) or -1 to remove the first element (like a queue dequeue). This is useful for maintaining fixed-size sliding windows or queue-like arrays without reading the array first.
// Remove the LAST element (stack behavior)
db.notifications.updateOne(
{ _id: userId },
{ $pop: { history: 1 } }
);
// Remove the FIRST element (queue behavior)
db.jobs.updateOne(
{ _id: workerId },
{ $pop: { queue: -1 } }
);
// Practical: sliding window of last 10 events
// After push: use $pop: { events: 1 } if length > 10The $pullAll Operator
$pullAll is a convenience operator that removes all instances of each specified value from an array. It's equivalent to using $pull with $in, but with a slightly simpler syntax when you have a fixed list of values to remove. Note: $pullAll matches exact values and cannot accept query operators.
// Remove multiple specific tags
db.articles.updateOne(
{ _id: articleId },
{ $pullAll: { tags: ['draft', 'wip', 'temp'] } }
);
// Equivalent to:
db.articles.updateOne(
{ _id: articleId },
{ $pull: { tags: { $in: ['draft', 'wip', 'temp'] } } }
);Combining Array Operators in One Update
You can combine multiple update operators in a single updateOne call, but you cannot apply two operators to the same field in one update. You can, for example, simultaneously $push to a tags array and $inc a count field in one atomic operation, reducing round-trips to the database.
// Push tag AND increment tagCount in one atomic update
db.articles.updateOne(
{ _id: articleId },
{
$push: { tags: 'mongodb' },
$inc: { tagCount: 1 },
$set: { updatedAt: new Date() }
}
);
// All three modifications are applied atomically$push vs $addToSet: Choosing the Right One
The key question when choosing between $push and $addToSet is: do you want to allow duplicates? Use $push when order matters, duplicates are valid, or you're modelling a log/history. Use $addToSet when the array represents a set of unique values like tags, roles, liked IDs, or subscriptions. $addToSet is slightly more expensive because MongoDB checks for existence before inserting.
// $push: suitable for ordered logs (duplicates OK)
db.sessions.updateOne(
{ _id: sessionId },
{ $push: { events: { type: 'click', ts: new Date() } } }
);
// $addToSet: suitable for unique sets
db.users.updateOne(
{ _id: userId },
{ $addToSet: { likedPostIds: postId } } // no duplicate likes
);Performance Considerations for Array Updates
Arrays that grow without bound cause document bloat and can exceed MongoDB's 16 MB document size limit. Common mitigation strategies include: using $push with $slice to cap the array at a maximum length; periodically running cleanup operations to remove old elements; or using the Bucket Pattern to group entries into time-bounded bucket documents instead of a single unbounded array.
// Cap array at last 100 notifications
db.users.updateOne(
{ _id: userId },
{
$push: {
notifications: {
$each: [newNotification],
$slice: -100, // keep only last 100 elements
$sort: { ts: 1 } // sort by timestamp first
}
}
}
);Quick Check
Test your understanding of array update operators in MongoDB.
Lesson Recap
In this lesson you learned: $push appends elements (with $each, $slice, $sort modifiers), $addToSet adds only unique values, $pull removes all matching elements, and $pop removes the first or last element by position. Next up we explore positional and filtered positional updates for modifying array elements in place.
자주 묻는 질문
“배열 업데이트하기: $push, $pull, $pop, $addToSet” 강의는 무료인가요?
네 — “배열 업데이트하기: $push, $pull, $pop, $addToSet” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“배열 업데이트하기: $push, $pull, $pop, $addToSet”에서 뭘 배우나요?
학습자는 배열 업데이트 연산자의 전체 집합을 사용해 문서 내부의 배열을 원자적으로 수정합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“배열 업데이트하기: $push, $pull, $pop, $addToSet” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 배열 쿼리하기: $all, $size, 요소 일치
- $elemMatch: 배열 하위 문서 일치시키기
- 배열 업데이트하기: $push, $pull, $pop, $addToSet
- 위치 지정 및 필터링된 위치 지정 업데이트