270

In Cloud Firestore there are three write operations:

  1. add()
  2. set()
  3. update()

In the docs it says that using set(object, { merge: true }) will merge the given object with the existing document.

The same happens when you use update(object)... so what is the difference? It seems strange that google would duplicate functionality like this.

6 Answers 6

603

The way I understood the difference:

  • set without merge will overwrite a document or create it if it doesn't exist yet

  • set with merge will update fields in the document or create it if it doesn't exists

  • update will update fields but will fail if the document doesn't exist

  • create will create the document but fail if the document already exists

There's also a difference in the kind of data you provide to set and update.

For set you always have to provide document-shaped data:

set(
  {a: {b: {c: true}}},
  {merge: true}
)

With update you can also use field paths for updating nested values:

update({
  'a.b.c': true
})
14
  • 6
    but where have you found create method in the API?
    – ZuzEL
    Oct 6, 2017 at 7:49
  • 2
    cloud.google.com/nodejs/docs/reference/firestore/0.8.x/… for node.js. It seems the web API doesn't have that method. Wasn't sure which platform you are on :)
    – Scarygami
    Oct 6, 2017 at 7:59
  • 35
    Another distinction you can mention is that set operates on document-shaped data, where update takes field path and value pairs. This means you can make changes to deeply nested values with update that are more cumbersome with set. For example: set({a: {b: {c: true}}}, {merge: true}) vs update('a.b.c', true). Oct 6, 2017 at 16:10
  • If I want to update a value in a document, It makes sense that I want to update documents that already exists, so I think set + mergeall is not that usefull because it will creat it the document does not exists Aug 11, 2018 at 21:12
  • 7
    set with merge option will overwrite the field no matter what. However update will be ignored if this is not the last update. For Example if you trigger the update action on an offline device, and get back online 3 days later. Oct 16, 2020 at 9:16
135

Another difference (extending Scarygami's answer) between "set with merge" and "update", is when working with a nested values.

if you have a document structured like this:

 {
   "friends": {
     "friend-uid-1": true,
     "friend-uid-2": true,
   }
 }

and want to add {"friend-uid-3" : true}

using this:

db.collection('users').doc('random-id').set({ "friends": { "friend-uid-3": true } },{merge:true})

will result in this data:

 {
   "friends": {
     "friend-uid-1": true,
     "friend-uid-2": true,
     "friend-uid-3": true
   }
 }

however update using this:

db.collection('users').doc('random-id').update({ "friends": { "friend-uid-3": true } })

will result in this data:

 `{
   "friends": {
     "friend-uid-3": true
   }
 }`
6
  • 1
    Have you tried testing this yourself? There is a section in the documentation: "To update some fields of a document without overwriting the entire document, use the update() method..."link Jun 6, 2018 at 10:03
  • yes I have tested this. It was a few weeks ago, but I am positive I came out with the result I wrote. I searched up why it didn't work as expected etc. I will test it out now.
    – ravo10
    Jun 6, 2018 at 10:16
  • 2
    I figured it out. I only tried this with an array before. Where I wanted to add an object to the array, and everything got overwritten for that array. It does not work with fields containing an array... it does stand it docs.
    – ravo10
    Jun 6, 2018 at 11:24
  • 2
    Just got to the same conclusion after tests. I hope they will add an option that has the same effect as { merge: true } to the update function.
    – Johnride
    Mar 13, 2019 at 0:47
  • 8
    To avoid overwriting data in nested fields (as in the answer above) when using update, you can use dot notation. The overwrite behavior of update is different if you do/don't use dot notation. Jan 15, 2020 at 17:05
24

Per docs: https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects

Dot notation allows you to update a single nested field without overwriting other nested field. If you update a nested field without dot notation, you will overwrite the entire map field.

As stated above, this replaces entire friends structure.

db.collection('users').doc('random-id').update({
    "friends": {
        "friend-uid-3": true
    }
})

This does not.

db.collection('users').doc('random-id').update({
    "friends.friend-uid-3": true
})
7

Further adding on to the answers above, if you want to delete nested fields in a map then you may want to use update or set depending on your use case.

If you start with the following and want to remove all profile entries other than "user1" then you have two options.

{
  "users": {
    "profiles": {
      "user1": ...,
      "user2": ...
    }
  }

Update

This will overwrite profiles with whatever is provided

update({
  'users.profiles': { 'user1': ... }
})

Set

This will merge the deletes into the existing profiles, leaving whatever wasn't deleted

set({
  users: {
    profiles: {
      'user2': FieldValue.delete(),
      'user3': FieldValue.delete(),
      ...
    }
  }
}, { merge: true })

This only applies to Maps because both set and update will overwrite arrays unless you explicitly use the array-specific operators such as arrayUnion.

0

Scarygami answer holds true for firebase version 9 as well. Small changes should be considered though:

  • use setDoc instead of set. For example, instead of using db.collection('users').doc('random-id').set({ 'admin': true });, use setDoc(doc(db, 'users', 'random-id'), { "admin": true })
  • use updateDoc instead of update. For example, instead of using db.collection('users').doc( random-id').update({"age": 27}), use await updateDoc(doc(db, 'users', 'random-id'), { "age": 27})
0

Both set with {merge: true} and update are used for modifying documents in Firestore, but they have different behaviors and use-cases:

set with {merge: true}

When you use set with the {merge: true} option, the fields you specify are merged into the existing document. If the document doesn't exist, a new document is created with the specified fields.

  • Creates a document if it doesn't exist: This is useful for upsert-like operations.
  • Overwrites specific fields: Only the fields you specify in the set operation will be overwritten; other fields will remain untouched.
  • Can add new fields: If you specify fields that don't currently exist in the document, they will be created.

Example:

const docRef = firestore.collection('users').doc('user1');
await docRef.set({
  name: "John",
  age: 30
}, { merge: true });

update

The update operation updates the values of specific fields in an existing document. Unlike set, it will not create a new document if the document doesn't already exist; you'll get an error instead.

  • Doesn't create a new document: Requires the document to already exist.
  • Field-level updates: You can update nested fields using "dot notation."
  • No addition of new fields: Unlike set with {merge: true}, which can add fields if they do not exist, update requires the fields to exist (although you can update nested fields).

Example:

const docRef = firestore.collection('users').doc('user1');
await docRef.update({
  "address.city": "San Francisco"
});

Summary

  • set with {merge: true}: Good for upsert-like operations. Creates the document if it doesn't exist and merges fields. Can add fields that don't currently exist in the document.

  • update: Only for updating existing documents. Updates can be applied to nested fields. Will error out if the document or fields don't exist.

Choose the one that best fits your use-case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.