31
votes

Can we change the name of a collection in Cloud Firestore? I have created a collection with 200 documents. Now I want to change the name of the collection. In the Firebase console, I could not find a way to do this.

Is it possible to change a collection's name either through code or in the console. Or Is it possible to export documents from Firestore, create a new collection and then import those documents again?

Please help.

3

3 Answers

39
votes

It's not possible to change the names or IDs or collections or documents once they exist. All that data is immutable, for the purpose of building efficient indexes.

You could certainly read everything out, then put it all back in with new names and IDs.

6
votes

You can load it then reupload it with the new name

      await FirebaseFirestore.instance
          .collection(oldCollectionName)
          .get()
          .then((QuerySnapshot snapShot) async {
        snapShot.docs.forEach((element) async {
          await FirebaseFirestore.instance
              .collection(newCollectionName)
              .doc(element.id)
              .set(element.data());
        });
      });

Note: the above code is written for flutter, but it might help anyone with little changes.

0
votes

Here is a piece of code written in JavaScript. Please consider that subcollections are not moved, and that the former collection is not destroyed.

const db = admin.firestore();
const oldCollRef = db.collection('oldCollectionName');
const oldCollSnap = await oldCollRef.get();
let arrayPromise = [];
oldCollSnap.forEach(async doc => {
    arrayPromise.push(new Promise(async (resolve, reject) => {
        resolve(await db.collection('newCollectionName').add(doc.data()));
    }));
})
Promise.all(arrayPromise)