80

As we can download json file at Firebase RTDB console, are there any way to export json file of Firestore collection/document data?

One of my main objectives is to compare data before/after updating document.

miz-k
  • 965
  • 1
  • 7
  • 9

15 Answers15

45

Google made it harder than it needed to be, so the community found a workaround. If you have npm installed, you can do this:

Export

npx -p node-firestore-import-export firestore-export -a credentials.json -b backup.json

Import

npx -p node-firestore-import-export firestore-import -a credentials.json -b backup.json

Source

gion
  • 3
  • 1
  • 2
Gunar Gessner
  • 2,331
  • 23
  • 23
  • 3
    This is the simplest for grabbing data in json format, and working as of this date. You'll need to get GCP service account credentials as seen at https://cloud.google.com/docs/authentication/production
    More docs: https://www.npmjs.com/package/firestore-export-import
    – ezaspi Oct 17 '20 at 13:58
  • That worked beautifully, thanks a lot! And thanks @ezaspi as well for the comment re: credentials – Greg Sadetsky Jun 23 '21 at 12:48
  • This command works great but on running this command does it count as a reads/writes to the firestore? – sh_ark Sep 18 '21 at 02:22
  • 2
    @sh_ark yes it counts towards your project's read/writes – Gunar Gessner Sep 18 '21 at 07:24
  • This is fantastic. Thanks! – Stephen Gilboy Sep 23 '21 at 03:24
  • how to setup "credential.json" file? I've downloaded the file from firebase service account settings but where to put it, because while running this command, I'm getting error saying can't find credential.json – Keval Langalia Mar 24 '22 at 22:50
  • @KevalLangalia Use the `-a` argument to point to the location of the file. The given example assumes that the `credentials.json` file resides is in the current folder. – Gunar Gessner Mar 24 '22 at 23:20
  • @GunarGessner well, I had credentials.json in same folder location but anyway, I decided to use `Firefoo` app to export the collections, and it worked! Appreciate your help. – Keval Langalia Mar 24 '22 at 23:35
  • Does this work on the spark plan of firestore? I think I read somewhere that you dont get access to some GCP feature until you provide creditCard details – sayandcode Aug 30 '22 at 12:37
39

I just wrote a backup and restore for Firestore. You can have a try on my GitHub.

https://github.com/dalenguyen/firestore-backup-restore

Thanks,

Dale Nguyen
  • 1,930
  • 3
  • 24
  • 37
33

There is not, you'd need to come up with your own process such as querying a collection and looping over everything.

Update

As of August 7th, 2018, we do have a managed export system that allows you to dump your data into a GCS bucket. While this isn't JSON, it is a format that is the same as Cloud Datastore uses, so BigQuery understands it. This means you can then import it into BigQuery.

Community
  • 1
  • 1
Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
  • 1
    Good news. import and export your Cloud Firestore data. Checkout the [blog](https://firebase.googleblog.com/2018/08/more-cloud-firestore-improvements.html) and [doc](https://firebase.google.com/docs/firestore/manage-data/export-import) for more info – Sivaraj S Aug 10 '18 at 01:24
  • 2
    @dan-mcgrath can you point to any information on sub-collections and how to be able to effectively query those once in BigQuery? – Ashton Thomas Sep 05 '18 at 17:05
  • 24
    What format is the exported file, and how could one see the contents? – Jan Krynauw Oct 31 '18 at 16:51
  • How can i export the dump to json format and and is there a way to zip all the dump files? – Haider Nov 29 '19 at 09:43
  • 1
    I cannot seem to find any information on what format the Firestore export is in. All options for file type in the BigQuery import UI give an error when I try to import the exported Firestore file. – ben_frankly Jul 30 '20 at 22:26
  • I found these comments while looking for an answer on the same question, how to view the contents of a Firestore export. There is a separate Firebase help article that tells you how to schedule daily Firestore exports for backup purposes. What the article does not tell you is that, if you are exporting all collections, then you will be unable to open the export file in BigQuery. Instead you need to import it back into Firestore using the Firestore Import/Export page in the GCP console. If you don't want to overwrite your existing Firestore, you can create a new Firebase project to import to. – most200 May 12 '22 at 21:06
15

I've written a tool that traverses the collections/documents of the database and exports everything into a single json file. Plus, it will import the same structure as well (helpful for cloning/moving Firestore databases). Since I've had a few colleagues use the code, I figured I would publish it as an NPM package. Feel free to try it and give some feedback.

https://www.npmjs.com/package/node-firestore-import-export

jloosli
  • 2,461
  • 2
  • 22
  • 34
  • 1
    Excellent best package I have found for this so far, especially the import very useful for multiple environment scenarios. Also I see you have to specify the path to credential file in the command would it be useful to have it first check for path in the environment variable GOOGLE_APPLICATION_CREDENTIALS otherwise can be overridden via the path parameter. – dynamiclynk Mar 30 '18 at 10:57
  • Also I put this in my package.json so I can just run "npm run firestore-export" or "import" – dynamiclynk Mar 30 '18 at 11:26
  • 1
    @wchoward I like the environment approach...I'll add that for the next version – jloosli Mar 30 '18 at 16:55
  • @wchoward I added GOOGLE_APPLICATION_CREDENTIALS support in version 0.8.0...check it out and let me know if it works for you. – jloosli Mar 30 '18 at 18:27
  • If i export a collection with huge data size its gives out of memory error – Haider Nov 27 '19 at 20:36
  • Thanks for this, but it already fails with ~100k registers. FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory – 1x2x3x4x Apr 16 '20 at 11:35
10

If someone wants a solution using Python 2 or 3.

Edit: note that this does not backup the rules

Fork it on https://github.com/RobinManoli/python-firebase-admin-firestore-backup

First install and setup Firebase Admin Python SDK: https://firebase.google.com/docs/admin/setup

Then install it in your python environment:

pip install firebase-admin

Install the Firestore module:

pip install google-cloud-core
pip install google-cloud-firestore

(from ImportError: Failed to import the Cloud Firestore library for Python)

Python Code

# -*- coding: UTF-8 -*-

import firebase_admin
from firebase_admin import credentials, firestore
import json

cred = credentials.Certificate('xxxxx-adminsdk-xxxxx-xxxxxxx.json') # from firebase project settings
default_app = firebase_admin.initialize_app(cred, {
    'databaseURL' : 'https://xxxxx.firebaseio.com'
})

db = firebase_admin.firestore.client()

# add your collections manually
collection_names = ['myFirstCollection', 'mySecondCollection']
collections = dict()
dict4json = dict()
n_documents = 0

for collection in collection_names:
    collections[collection] = db.collection(collection).get()
    dict4json[collection] = {}
    for document in collections[collection]:
        docdict = document.to_dict()
        dict4json[collection][document.id] = docdict
        n_documents += 1

jsonfromdict = json.dumps(dict4json)

path_filename = "/mypath/databases/firestore.json"
print "Downloaded %d collections, %d documents and now writing %d json characters to %s" % ( len(collection_names), n_documents, len(jsonfromdict), path_filename )
with open(path_filename, 'w') as the_file:
    the_file.write(jsonfromdict)
benomatis
  • 5,536
  • 7
  • 36
  • 59
Robin Manoli
  • 2,162
  • 2
  • 25
  • 30
8

There is an npm for firestore export / import

Project to export Goto -> project settings -> Service account -> Generate new private key -> save it as exportedDB.json

Project to import Goto -> project settings -> Service account -> Generate new private key -> save it as importedDB.json

run these 2 commands from the folder where u saved the files

Export: npx -p node-firestore-import-export firestore-export -a exportedDB.json -b backup.json

Import: npx -p node-firestore-import-export firestore-import -a importedDB.json -b backup.json

Dharman
  • 30,962
  • 25
  • 85
  • 135
Hezy Ziv
  • 3,652
  • 2
  • 14
  • 8
3

Firestore is still early in its development so please check the docs on backups for any information pertaining to Firestore.

I found this npm package, node-firestore-backup, to be easy and useful.

Note that the --accountCredentials path/to/credentials/file.json is referring to a service account key json file that you can get by following instructions from https://developers.google.com/identity/protocols/application-default-credentials.

  1. Go to the API Console Credentials page.
  2. From the project drop-down, select your project.
  3. On the Credentials page, select the Create credentials drop-down, then select Service account key.
  4. From the Service account drop-down, select an existing service account or create a new one.
  5. For Key type, select the JSON key option, then select Create. The file automatically downloads to your computer.
  6. Put the *.json file you just downloaded in a directory of your choosing. This directory must be private (you can't let anyone get access to this), but accessible to your web server code.
willhlaw
  • 39
  • 1
3

It works for me.

I used Cloud Functions to export all data in Firestore to JSON format. The function that I was used:

exports.exportFirestore2Json = functions.https.onRequest((request, response) => {
    db.collection("data").get().then(function(querySnapshot) {
        const orders = [];
        var order = null

         querySnapshot.forEach(doc => {
             order = doc.data();
             orders.push(order);
         });

         response.send(JSON.stringify(orders))

         return true
    })
    .catch(function(error) {
        console.error("Error adding document: ", error);
        return false
    });
})

Then, go to https://your-project-id.cloudfunctions.net/exportFirestore2Json you will see something like this

enter image description here

benomatis
  • 5,536
  • 7
  • 36
  • 59
Albert Khang
  • 621
  • 6
  • 17
2

Yes you can, you did not need to start billing in your firebase console. There is a great npm package https://www.npmjs.com/package/firestore-export-import with this you can export and import firestore collection and documents easily. Just follow some steps:

-Get your service account key Open Firebase console > Project settings > Service accounts > generate new private key

rename the downloaded file with serviceAccountKey.json

-Now create a new folder and index.js file.

-Paste you servicekey.json in this folder

-Now install this package

npm install firestore-export-import

OR

yarn add firestore-export-import

Exporting data from firebase

const { initializeApp} =  require('firestore-export-import')

const  serviceAccount  =  require('./serviceAccountKey.json')

const  appName  =  '[DEFAULT]'

initializeApp(serviceAccount, appName)

const  fs  =  require('fs');

const { backup } =  require('firestore-export-import')
//backup('collection name')

backup('users').then((data) =>
{
    const  json  =  JSON.stringify(data);

    //where collection.json is your output file name.
    fs.writeFile('collection.json', json, 'utf8',()=>{

    console.log('done');

})

});

Execute node index.js and you should see a new collection.json file with your collection and documents in it. If it looks a little messy pretty format it online with https://codebeautify.org/jsonviewer

This index.js was just a very basic configuration which exports the whole collection with everything in it, read their documentation you could do queries and much more!

Importing data to firebase

const { initializeApp,restore } =  require('firestore-export-import')

const  serviceAccount  =  require('./serviceAccountKey.json')
const  appName  =  '[DEFAULT]'

initializeApp(serviceAccount, appName)
restore('collection.json', {
//where refs is an array of key items
    refs: ['users'],
    //autoParseDates to parse dates if documents have timestamps
    autoParseDates: true,

    },()=>{

console.log('done');
})

After execution you should see your firestore populated with collection users!

benomatis
  • 5,536
  • 7
  • 36
  • 59
Arihant Jain
  • 817
  • 5
  • 17
  • something is missing in code. getting error "initializeApp() is not a function", can you help by mentioning exact code or any import i need to do in code? – Keval Langalia Mar 24 '22 at 22:58
  • var admin = require("firebase-admin"); const serviceAccount = require('./serviceAccountKey.json') admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://playbae-3fdc0.firebaseio.com" }); const fs = require('fs'); const { backup } = require('firestore-export-import') //backup('collection name') backup('Users').then((data) => { const json = JSON.stringify(data); //where collection.json is your output file name. fs.writeFile('collection.json', json, 'utf8',()=>{ console.log('done'); }) }); – Faiz Ul Hassan Apr 12 '22 at 16:53
2

for dumping json from your local to firestoreDB:

npx -p node-firestore-import-export firestore-import -a credentials.json -b backup.json

for downloading data from firestoreDB to your local:

npx -p node-firestore-import-export firestore-export -a credentials.json -b backup.json

to generate credentials.json, go to project settings -> service accounts -> generate a private key.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
1
  1. Create a blank folder (call it firebaseImportExport ) and run npm init
  2. Go to the source Firebase project -> Settings -> Service Accounts
  3. Click on the Generate new private key button and rename the file as source.json and put it in the firebaseImportExport folder
  4. Do the same (step 2 & 3) for the destination project and rename the file as destination.json
  5. Install the npm i firebase-admin npm package.
  6. Write the following code in the index.js
const firebase = require('firebase-admin');

var serviceAccountSource = require("./source.json");
var serviceAccountDestination = require("./destination.json");

const sourceAdmin = firebase.initializeApp({
    credential: firebase.credential.cert(serviceAccountSource),
    databaseURL: "https://**********.firebaseio.com" // replace with source
});

const destinationAdmin = firebase.initializeApp({
    credential: firebase.credential.cert(serviceAccountDestination),
    databaseURL: "https://$$$$$.firebaseio.com"
  }, "destination");

const collections = [ "books", "authors",   ...]; // replace with your collections

    var source = sourceAdmin.firestore();
    var destination = destinationAdmin.firestore();
   collections.forEach(colName => {
    source.collection(colName).get().then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            destination.collection(colName).doc(doc.id).set({...doc.data()});
        });
    });
   });
benomatis
  • 5,536
  • 7
  • 36
  • 59
1

Documents can also be downloaded as JSON via the REST API.

This is an example using curl in conjunction with the Cloud SDK to obtain an access token:

curl -H "Authorization: Bearer "$(gcloud auth print-access-token) \
  "https://firestore.googleapis.com/v1/projects/$PROJECT/databases/(default)/documents/$COLLECTION/$DOCUMENT"
Andreas Klöber
  • 5,855
  • 2
  • 27
  • 20
0

Open any of your clientside firebase apps (React, Angular, etc.). Use this code anywhere to log console and copy

const products = await db
  .collection("collectionName")
  .where("time", ">", new Date("2020-09-01"))
  .get()


const json = JSON.stringify(products.docs.map((doc) => ({ ...doc.data() })))
console.log(json)
benomatis
  • 5,536
  • 7
  • 36
  • 59
Nagibaba
  • 4,218
  • 1
  • 35
  • 43
0

I found an easier solution. There is a tool called Firefoo. It lists all the collection documents along with created users with multiple providers(email & password, phone number, google, facebook etc). You can export data in JSON & CSV along with that you can view the data in simplified format like Table, Tree, JSON.

Note:- You don't have to go through all the process for importing or exporting data from your firebase console.

Ayub Alam
  • 1
  • 2
0

Create a blank folder (Ex: firebaseImportExport ) and run npm init

Go to the source Firebase project -> Settings -> Service Accounts

Click on the Generate new private key button and rename the file as appConfig.json and put it in the firebaseImportExport folder

add packages

npm install firestore-export-import

create an index.js file.

paste the below code

const { initializeFirebaseApp } = require('firestore-export-import')

const  serviceAccount  =  require('./appConfig.json')

const  appName  =  '[DEFAULT]'

const firestore = initializeFirebaseApp(serviceAccount, appName)

const  fs  =  require('fs');

const { backup } = require('firestore-export-import')
//backup('collection name')

backup(firestore, 'collection-name').then((data) =>
{
    const  json  =  JSON.stringify(data);

    //where collection.json is your output file name.
    fs.writeFile('collection.json', json, 'utf8',()=>{

    console.log('done');

})

});