Learning MongoDB

0% completed

Previous
Next
Array Operators

Array operators in MongoDB are used to manipulate arrays within documents. These operators enable you to add, remove, and update elements within arrays, as well as perform various operations on the array elements.

Understanding these operators is essential for effectively managing documents that contain array fields.

Array Operators

OperatorDescription
$addToSetAdds elements to an array only if they do not already exist in the array.
$popRemoves the first or last item of an array.
$pullRemoves all array elements that match a specified query.
$pushAdds an item to an array.
$pullAllRemoves all occurrences of the specified values from an array.
$eachModifies the $push and $addToSet operators to add multiple items to an array.
$sliceLimits the number of array elements during an update operation.
$sortSorts array elements during an update operation.
$positionSpecifies the position in the array to add elements.
$elemMatchMatches documents that contain an array field with at least one element that matches all the specified query criteria.

Syntax for Using Array Operators

The general syntax for using array operators in MongoDB is:

db.collection.updateOne( { <filter> }, { <arrayOperator>: { <field>: <value> } }, <options> )
  • filter: The criteria to match documents for the update.
  • arrayOperator: The array operator to apply.
  • field: The field to update.
  • value: The new value for the field.
  • options (optional): Additional options for the update operation.

Example Setup

First, let's insert some documents into the users collection to work with:

db.users.insertMany([ { name: "Alice", hobbies: ["reading", "traveling"], scores: [85, 90, 88] }, { name: "Bob", hobbies: ["cycling", "hiking"], scores: [78, 82, 79] }, { name: "Charlie", hobbies: ["gaming", "reading"], scores: [92, 85, 90] }, { name: "David", hobbies: ["swimming", "biking"], scores: [88, 84, 89] }, { name: "Eve", hobbies: ["running", "painting"], scores: [80, 86, 81] } ])

$addToSet Operator

The $addToSet operator adds elements to an array only if they do not already exist in the array. This ensures that there are no duplicate values in the array.

Examples

  1. Add a Hobby to Alice's Hobbies

    db.users.updateOne( { name: "Alice" }, { $addToSet: { hobbies: "swimming" } } )

    This command adds "swimming" to the hobbies array for the document where the name is "Alice" only if "swimming" is not already present in the array.

  2. Add Multiple Hobbies to Bob's Hobbies

    db.users.updateOne( { name: "Bob" }, { $addToSet: { hobbies: { $each: ["running", "climbing"] } } } )

    This command adds "running" and "climbing" to the hobbies array for the document where the name is "Bob" only if they are not already present in the array.

$pop Operator

The $pop operator removes the first or last item of an array. A value of -1 removes the first element, and a value of 1 removes the last element.

Examples

  1. Remove the First Hobby from Alice's Hobbies

    db.users.updateOne( { name: "Alice" }, { $pop: { hobbies: -1 } } )

    This command removes the first element from the hobbies array for the document where the name is "Alice". If the hobbies array is ["reading", "traveling"], it will become ["traveling"].

  2. Remove the Last Score from Bob's Scores

    db.users.updateOne( { name: "Bob" }, { $pop: { scores: 1 } } )

    This command removes the last element from the scores array for the document where the name is "Bob". If the scores array is [78, 82, 79], it will become [78, 82].

$pull Operator

The $pull operator removes all array elements that match a specified query.

Examples

  1. Remove a Specific Hobby from Alice's Hobbies

    db.users.updateOne( { name: "Alice" }, { $pull: { hobbies: "traveling" } } )

    This command removes all occurrences of the hobby "traveling" from the hobbies array for the document where the name is "Alice". If the hobbies array is ["reading", "traveling"], it will become ["reading"].

  2. Remove Scores Less Than 80 from Bob's Scores

    db.users.updateOne( { name: "Bob" }, { $pull: { scores: { $lt: 80 } } } )

    Explanation: This command removes all scores less than 80 from the scores array for the document where the name is "Bob". If the scores array is [78, 82, 79], it will become [82].

$push Operator

The $push operator adds an item to an array. This operator appends the specified value to the array.

Examples

  1. Add a New Hobby to Alice's Hobbies

    db.users.updateOne( { name: "Alice" }, { $push: { hobbies: "writing" } } )

    This command appends "writing" to the hobbies array for the document where the name is "Alice". If the hobbies array is ["reading", "traveling"], it will become ["reading", "traveling", "writing"].

  2. Add Multiple Scores to Bob's Scores

    db.users.updateOne( { name: "Bob" }, { $push: { scores: { $each: [75, 88] } } } )

    Explanation: This command appends 75 and 88 to the scores array for the document where the name is "Bob". If the scores array is [78, 82, 79], it will become [78, 82, 79, 75, 88].

$pullAll Operator

The $pullAll operator removes all occurrences of the specified values from an array.

Examples

  1. Remove Multiple Hobbies from Alice's Hobbies

    db.users.updateOne( { name: "Alice" }, { $pullAll: { hobbies: ["reading", "traveling"] } } )

    This command removes "reading" and "traveling" from the hobbies array for the document where the name is "Alice". If the hobbies array is ["reading", "traveling", "writing"], it will become ["writing"].

  2. Remove Multiple Scores from Bob's Scores

    db.users.updateOne( { name: "Bob" }, { $pullAll: { scores: [78, 82] } } )

    This command removes 78 and 82 from the scores array for the document where the name is "Bob". If the scores array is [78, 82, 79], it will become [79].

$each Operator

The $each operator modifies the $push and $addToSet operators to add multiple items to an array.

Examples

  1. Add Multiple Hobbies to Alice's Hobbies

    db.users.updateOne( { name: "Alice" }, { $push: { hobbies: { $each: ["swimming", "biking"] } } } )

    This command appends "swimming" and "biking" to the hobbies array for the document where the name is "Alice". If the hobbies array is ["reading", "traveling"], it will become ["reading", "traveling", "swimming", "biking"].

$sort Operator

The $sort operator sorts array elements during an update operation. It can be used in conjunction with $push to maintain a sorted array.

Examples

  1. Add Multiple Hobbies to Alice's Hobbies and Sort the Array

    db.users.updateOne( { name: "Alice" }, { $push: { hobbies: { $each: ["swimming", "biking"], $sort: 1 } } } )

    This command appends "swimming" and "biking" to the hobbies array and then sorts the array in ascending order. If the hobbies array is ["reading", "traveling"], it will become ["biking", "reading", "swimming", "traveling"].

  2. Add Multiple Scores to Bob's Scores and Sort the Array

    db.users.updateOne( { name: "Bob" }, { $push: { scores: { $each: [75, 88], $sort: -1 } } } )

    Explanation: This command appends 75 and 88 to the scores array and then sorts the array in descending order. If the scores array is [78, 82, 79], it will become [88, 82, 79, 78, 75].

$position Operator

The $position operator specifies the position in the array to add elements. It can be used in conjunction with $push to insert elements at a specific index.

Examples

  1. Add a Hobby to a Specific Position in Alice's Hobbies

    db.users.updateOne( { name: "Alice" }, { $push: { hobbies: { $each: ["swimming"], $position: 1 } } } )

    This command inserts "swimming" at the second position in the hobbies array (index 1) for the document where the name is "Alice". If the hobbies array is ["reading", "traveling"], it will become ["reading", "swimming", "traveling"].

  2. Add a Score to a Specific Position in Bob's Scores

    db.users.updateOne( { name: "Bob" }, { $push: { scores: { $each: [85], $position: 2 } } } )

    This command inserts 85 at the third position in the scores array (index 2) for the document where the name is "Bob". If the scores array is [78, 82, 79], it will become [78, 82, 85, 79].

$elemMatch Operator

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

Examples

  1. Find Users with a Specific Hobby and Score

    db.users.find( { hobbies: { $elemMatch: { $eq: "reading" } }, scores: { $elemMatch: { $gt: 80 } } } )

    This query finds documents where the hobbies array contains "reading" and the scores array contains at least one element greater than 80. For example, it will match the document for "Alice" if her hobbies are ["reading", "traveling"] and her scores are [85, 90, 88].

  2. Find Users with Multiple Matching Scores

    db.users.find( { scores: { $elemMatch: { $gte: 80, $lte: 90 } } } )

    This query finds documents where the scores array contains at least one element that is between 80 and 90, inclusive. For example, it will match the document for "Charlie" if his scores are [92, 85, 90].

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next