Bird
Raised Fist0
Firebasecloud~10 mins

Array update operations (arrayUnion, arrayRemove) in Firebase - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Array update operations (arrayUnion, arrayRemove)
Start with existing array
↓
Choose operation: arrayUnion or arrayRemove
↓
arrayUnion
↓
Update array in database
↓
Done
This flow shows how arrayUnion adds unique elements and arrayRemove deletes matching elements from an array in the database.
Execution Sample
Firebase
docRef.update({ tags: firebase.firestore.FieldValue.arrayUnion('new') });
docRef.update({ tags: firebase.firestore.FieldValue.arrayRemove('old') });
This code adds 'new' to the tags array if not present, and removes 'old' from the tags array if present.
Process Table
StepOperationInput ArrayValue to Add/RemoveResulting ArrayAction Description
1Start['red', 'blue']--Initial array in document
2arrayUnion['red', 'blue']'green'['red', 'blue', 'green']Add 'green' because it is not present
3arrayUnion['red', 'blue', 'green']'blue'['red', 'blue', 'green']Do not add 'blue' again, already present
4arrayRemove['red', 'blue', 'green']'blue'['red', 'green']Remove 'blue' from array
5arrayRemove['red', 'green']'yellow'['red', 'green']No change, 'yellow' not in array
6End['red', 'green']--Final array after updates
💡 No more operations, array updated with union and remove as requested
Status Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
tags['red', 'blue']['red', 'blue', 'green']['red', 'blue', 'green']['red', 'green']['red', 'green']['red', 'green']
Key Moments - 3 Insights
Why doesn't arrayUnion add a duplicate element if it already exists?
arrayUnion only adds elements that are not already in the array, as shown in step 3 where 'blue' is not added again.
What happens if arrayRemove tries to remove an element not in the array?
No change occurs to the array, as shown in step 5 where 'yellow' is not found and the array remains the same.
Does arrayUnion modify the original array or create a new one?
It updates the array in place in the database by adding unique elements, as seen in steps 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the array after step 2?
A['red', 'blue']
B['red', 'blue', 'green']
C['green']
D['red', 'blue', 'green', 'blue']
💡 Hint
Check the 'Resulting Array' column in row for step 2
At which step does the array stop changing because the element to add is already present?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Action Description' for step 3 in the execution table
If we try to remove 'red' instead of 'yellow' at step 5, what would the array be?
A['red', 'green']
B['red']
C['green']
D['yellow']
💡 Hint
Refer to how arrayRemove works in step 4 and apply it to step 5
Concept Snapshot
arrayUnion(value) adds value only if not already in array
arrayRemove(value) removes all instances of value
Both update the array atomically in the database
Use to safely add or remove elements without duplicates
No duplicates added by arrayUnion
No error if removing non-existent elements
Full Transcript
This lesson shows how Firebase's arrayUnion and arrayRemove update arrays in documents. arrayUnion adds new unique elements, skipping duplicates. arrayRemove deletes all matching elements if present. The execution table traces an example array through adding 'green', skipping duplicate 'blue', removing 'blue', and attempting to remove non-existent 'yellow'. The variable tracker shows the array's state after each operation. Key moments clarify why duplicates are not added and what happens when removing missing elements. The quiz tests understanding of array states at each step. This helps beginners see how these operations safely update arrays in Firestore.

Practice

(1/5)
1. What does the arrayUnion operation do in Firebase Firestore?
easy
A. Removes all elements from an array field
B. Adds unique elements to an array field without duplicates
C. Replaces the entire array with a new one
D. Sorts the array elements in ascending order

Solution

  1. Step 1: Understand arrayUnion purpose

    The arrayUnion operation adds elements to an array field only if they are not already present, ensuring no duplicates.
  2. Step 2: Compare with other options

    The other options describe removing all elements, replacing the array, or sorting, which are not what arrayUnion does.
  3. Final Answer:

    Adds unique elements to an array field without duplicates -> Option B
  4. Quick Check:

    arrayUnion adds unique items without duplicates [OK]
Hint: arrayUnion only adds new unique items to arrays [OK]
Common Mistakes:
  • Thinking arrayUnion removes items
  • Confusing arrayUnion with replacing arrays
  • Assuming arrayUnion sorts the array
2. Which of the following is the correct syntax to add an element 'blue' to an array field 'colors' using arrayUnion in Firestore?
easy
A. docRef.update({ colors: arrayUnion('blue') })
B. docRef.update({ colors: arrayRemove('blue') })
C. docRef.set({ colors: arrayUnion('blue') })
D. docRef.add({ colors: arrayUnion('blue') })

Solution

  1. Step 1: Identify correct method for updating fields

    To update an existing document's field, update() is used, not set() or add().
  2. Step 2: Use arrayUnion to add element

    The syntax arrayUnion('blue') correctly adds 'blue' to the array without duplicates.
  3. Final Answer:

    docRef.update({ colors: arrayUnion('blue') }) -> Option A
  4. Quick Check:

    Use update() with arrayUnion() to add items [OK]
Hint: Use update() with arrayUnion() to add array items [OK]
Common Mistakes:
  • Using arrayRemove instead of arrayUnion
  • Using set() which overwrites the whole document
  • Using add() which is for collections, not fields
3. Given the Firestore document field tags: ['news', 'tech'], what will be the value of tags after this update?
docRef.update({ tags: arrayUnion('tech', 'science') })
medium
A. ['news', 'tech', 'science']
B. ['news', 'science']
C. ['tech', 'science']
D. ['news', 'tech', 'tech', 'science']

Solution

  1. Step 1: Understand arrayUnion behavior with existing elements

    arrayUnion adds only new unique elements. 'tech' already exists, so it won't be duplicated.
  2. Step 2: Add new element 'science'

    'science' is new, so it will be added to the array.
  3. Final Answer:

    ['news', 'tech', 'science'] -> Option A
  4. Quick Check:

    arrayUnion adds only new unique items [OK]
Hint: arrayUnion skips duplicates, adds only new items [OK]
Common Mistakes:
  • Expecting duplicates to be added
  • Thinking arrayUnion removes items
  • Confusing arrayUnion with arrayRemove
4. You want to remove the string 'urgent' from the array field 'labels' in a Firestore document. Which code snippet contains an error?
medium
A. docRef.update({ labels: arrayRemove('urgent', 'important') })
B. docRef.update({ labels: arrayRemove(['urgent']) })
C. docRef.update({ labels: arrayRemove() })
D. docRef.update({ labels: arrayRemove('urgent') })

Solution

  1. Step 1: Check valid usage of arrayRemove

    arrayRemove requires at least one argument specifying which elements to remove.
  2. Step 2: Analyze each option

    docRef.update({ labels: arrayRemove() }) calls arrayRemove with no arguments, which is invalid and causes an error.
    docRef.update({ labels: arrayRemove(['urgent']) }) attempts to remove the array ['urgent'] (won't match/remove string 'urgent').
    docRef.update({ labels: arrayRemove('urgent', 'important') }) removes both if present.
    docRef.update({ labels: arrayRemove('urgent') }) correctly removes 'urgent'.
  3. Final Answer:

    docRef.update({ labels: arrayRemove() }) -> Option C
  4. Quick Check:

    arrayRemove needs at least one element argument [OK]
Hint: arrayRemove must have at least one element argument [OK]
Common Mistakes:
  • Calling arrayRemove with no arguments
  • Passing an array inside arrayRemove instead of elements
  • Confusing arrayRemove with arrayUnion
5. You have a Firestore document with an array field participants: ['alice', 'bob', 'carol']. You want to update it so that 'bob' is removed and 'dave' is added, ensuring no duplicates. Which update code achieves this?
hard
A. docRef.update({ participants: arrayRemove('bob'), participants: arrayUnion('dave') })
B. docRef.update({ participants: arrayRemove('bob', 'dave') })
C. docRef.update({ participants: arrayUnion('dave') })
D. docRef.update({ participants: arrayRemove('bob') }); docRef.update({ participants: arrayUnion('dave') })

Solution

  1. Step 1: Understand Firestore update limitations

    You cannot apply both arrayRemove and arrayUnion to the same field in a single update object (duplicate keys overwrite, only last applies).
  2. Step 2: Analyze options

    docRef.update({ participants: arrayRemove('bob'), participants: arrayUnion('dave') }): duplicate keys, only arrayUnion('dave') applies (adds 'dave', keeps 'bob').
    docRef.update({ participants: arrayRemove('bob', 'dave') }): removes 'bob' ('dave' ignored since absent), no add.
    docRef.update({ participants: arrayUnion('dave') }): adds 'dave', no remove.
    docRef.update({ participants: arrayRemove('bob') }); docRef.update({ participants: arrayUnion('dave') }): first removes 'bob', then adds 'dave' -> ['alice', 'carol', 'dave'].
  3. Final Answer:

    docRef.update({ participants: arrayRemove('bob') }); docRef.update({ participants: arrayUnion('dave') }) -> Option D
  4. Quick Check:

    Repeated keys overwrite; combine operations carefully [OK]
Hint: Firestore update keys must be unique; combine operations carefully [OK]
Common Mistakes:
  • Using duplicate keys in update object
  • Expecting multiple updates in one call with repeated keys
  • Not using transactions for complex updates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard