Array update operations (arrayUnion, arrayRemove) in Firebase - Time & Space Complexity
When updating arrays in Firebase, it's important to know how the time taken grows as the array gets bigger.
We want to understand how the operations arrayUnion and arrayRemove behave as more items are involved.
Analyze the time complexity of these Firebase array update operations.
const docRef = firestore.collection('users').doc('user1');
// Add items to array if not present
await docRef.update({
tags: firebase.firestore.FieldValue.arrayUnion('newTag')
});
// Remove items from array if present
await docRef.update({
tags: firebase.firestore.FieldValue.arrayRemove('oldTag')
});
This code adds or removes elements from an array field in a Firestore document.
Look at what happens repeatedly when these operations run.
- Primary operation: Checking if the item exists in the array and then adding or removing it.
- How many times: This check happens for each element in the array during the update.
As the array size grows, the time to check and update grows too.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | About 10 checks to find or remove the item |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of checks grows directly with the array size.
Time Complexity: O(n)
This means the time to add or remove an item grows linearly with the number of items in the array.
[X] Wrong: "Adding or removing an item from the array is always instant, no matter the size."
[OK] Correct: Firebase must check the whole array to avoid duplicates or to find the item to remove, so bigger arrays take more time.
Understanding how array updates scale helps you explain performance in real apps and shows you think about efficient data handling.
What if Firebase stored arrays as sets internally? How would that change the time complexity of arrayUnion and arrayRemove?
Practice
arrayUnion operation do in Firebase Firestore?Solution
Step 1: Understand arrayUnion purpose
ThearrayUnionoperation adds elements to an array field only if they are not already present, ensuring no duplicates.Step 2: Compare with other options
The other options describe removing all elements, replacing the array, or sorting, which are not whatarrayUniondoes.Final Answer:
Adds unique elements to an array field without duplicates -> Option BQuick Check:
arrayUnion adds unique items without duplicates [OK]
- Thinking arrayUnion removes items
- Confusing arrayUnion with replacing arrays
- Assuming arrayUnion sorts the array
arrayUnion in Firestore?Solution
Step 1: Identify correct method for updating fields
To update an existing document's field,update()is used, notset()oradd().Step 2: Use arrayUnion to add element
The syntaxarrayUnion('blue')correctly adds 'blue' to the array without duplicates.Final Answer:
docRef.update({ colors: arrayUnion('blue') }) -> Option AQuick Check:
Use update() with arrayUnion() to add items [OK]
- Using arrayRemove instead of arrayUnion
- Using set() which overwrites the whole document
- Using add() which is for collections, not fields
tags: ['news', 'tech'], what will be the value of tags after this update?docRef.update({ tags: arrayUnion('tech', 'science') })Solution
Step 1: Understand arrayUnion behavior with existing elements
arrayUnion adds only new unique elements. 'tech' already exists, so it won't be duplicated.Step 2: Add new element 'science'
'science' is new, so it will be added to the array.Final Answer:
['news', 'tech', 'science'] -> Option AQuick Check:
arrayUnion adds only new unique items [OK]
- Expecting duplicates to be added
- Thinking arrayUnion removes items
- Confusing arrayUnion with arrayRemove
Solution
Step 1: Check valid usage of arrayRemove
arrayRemove requires at least one argument specifying which elements to remove.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'.Final Answer:
docRef.update({ labels: arrayRemove() }) -> Option CQuick Check:
arrayRemove needs at least one element argument [OK]
- Calling arrayRemove with no arguments
- Passing an array inside arrayRemove instead of elements
- Confusing arrayRemove with arrayUnion
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?Solution
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).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'].Final Answer:
docRef.update({ participants: arrayRemove('bob') }); docRef.update({ participants: arrayUnion('dave') }) -> Option DQuick Check:
Repeated keys overwrite; combine operations carefully [OK]
- Using duplicate keys in update object
- Expecting multiple updates in one call with repeated keys
- Not using transactions for complex updates
Ready to prove it?
Pass the test and this pattern moves unknown
