Introduction
MongoDB is a powerful NoSQL database that is widely used for storing and managing document-based information. One of the common tasks while working with MongoDB is manipulating arrays within documents. Appending values to an array field in a collection is an operation you’ll frequently perform. In this tutorial, we’ll take a thorough look at how to append values to an array field in MongoDB using several examples ranging from basic to advanced.
In MongoDB, we manipulate documents and their arrays primarily using the update()
and updateMany()
methods along with some special update operators.
Basic Usage of $push
Operator
The $push
operator in MongoDB is used to append a value to an array field. If the field is absent in the document to update, $push
adds the array field with the value as its element, unless the value is an array itself. Let us consider an example where we have a collection named posts
and we would like to append a tag to the tags
array of our post documents.
// Sample document before the update
// {
// 'title': 'Introduction to MongoDB',
// 'tags': ['database', 'nosql']
// }
db.posts.update(
{ 'title': 'Introduction to MongoDB' },
{ $push: { 'tags': 'big data' } }
);
// Sample document after the update
// {
// 'title': 'Introduction to MongoDB',
// 'tags': ['database', 'nosql', 'big data']
// }
Appending Multiple Values
If you want to append multiple values to an array field, you can use the $each
modifier with the $push
operator. This allows you to add more than one value to the respective field.
db.posts.update(
{ 'title': 'Introduction to MongoDB' },
{ $push: { 'tags': { $each: ['open source', 'document-oriented'] } } }
);
// Now the 'tags' array will be:
// ['database', 'nosql', 'big data', 'open source', 'document-oriented']
Using $position
to Control Insert Location
By default, when you append an element using the $push
operator, MongoDB adds the value to the end of the array. However, if you need to insert an element at a specific position within the array, you can accommodate the $position
modifier. The following example demonstrates this technique:
db.posts.update(
{ 'title': 'Introduction to MongoDB' },
{ $push: {
'tags': {
$each: ['community'],
$position: 0
}
}}
);
// The 'tags' array will now look like this:
// ['community', 'database', 'nosql', 'big data', 'open source', 'document-oriented']
Conditional Appending with $ne
and $addToSet
Sometimes you might want to append a value only if it doesn’t already exist in the array. MongoDB offers a couple of ways to handle this scenario. You can perform a conditional update using the $ne
(not equal) operator in conjunction with $push
, or you can use the $addToSet
operator which automatically prevents duplicates.
// Using $ne with $push
db.posts.update(
{ 'title': 'Introduction to MongoDB', 'tags': { $ne: 'mongodb' } },
{ $push: {'tags': 'mongodb'} }
);
// Using $addToSet (will only add 'mongodb' if it isn't present)
db.posts.update(
{ 'title': 'Introduction to MongoDB' },
{ $addToSet: { 'tags': 'mongodb' } }
);
// In both cases, the array will only include 'mongodb' once.
Advanced: The $slice
Modifier
In addition to appending values, you may want to control the size of an array. The $slice
modifier can be used to limit the array size during the pushing of a new value. This is specifically useful for maintaining fixed-size arrays, like a leaderboard, or to keep the most recent entries.
db.posts.update(
{ 'title': 'Introduction to MongoDB' },
{ $push: {
'tags': {
$each: ['BezKoder', 'Tutorial'],
$slice: -5 // Keep only the last 5 elements
}
}}
);
// This operation limits the 'tags' array to the last 5 elements.
The Upsert Option
Occasionally, you might perform an update operation where the document doesn’t exist yet, and you’d like to create it. MongoDB’s upsert
option comes in handy. When set to true
, it creates a new document if no matching documents are found for the update query.
db.posts.update(
{ 'title': 'Introduction to GraphQL' },
{ $push: { 'tags': 'query language' } },
{ upsert: true }
);
// If a post with the title 'Introduction to GraphQL' does not exist,
// this operation will create a new post document and add the specified tag.
Appending to Arrays in Embedded Documents
Working with nested arrays may require updating arrays within embedded documents. Using the dot notation, you can specify the path to the embedded document’s array and perform the push operation.
db.users.update(
{ 'username': 'jdoe' },
{ $push: { 'comments.upvotes': 'user123' } }
);
// If 'comments' is an array of comment objects, 'upvotes' being an array of usernames within each,
// this code will append 'user123' to the 'upvotes' array of 'jdoe's comments.
Conclusion
Appending values to array fields in MongoDB offers flexibility and control over your collections. Whether you’re adding a single value, preventing duplicates, controlling array size, or dealing with embedded arrays, MongoDB provides operators to cover your use cases. You should now feel confident in appending values to arrays within your MongoDB collections, enabling you to effectively manage array-based data structures.