Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.


+1 vote

When adding entries into my firebase database, I create multiple documents for each time I add entries. This is a problem since I only want to have 1 set of values to save and change. Is there a way to reference a single document to work with at a time in my code?

Here is a snippet of my code that I use to add elements to the database and it creates random document IDs that it grabs from randomly when I get() values:

FirebaseFirestore db = FirebaseFirestore.getInstance();

asked ago in CSC490_Spring202021 by (421 points)

1 Answer

0 votes

Note: In the past, most student projects have used the "Realtime Database" rather than the "Cloud Firestore". There are pros & cons. Comparison here: https://firebase.google.com/docs/firestore/rtdb-vs-firestore

As you probably realized, your current code is adding a new document to the collection. This is very useful, say, whenever a user posts something new on a message board, and you want to create a new "post" object with a unique ID to represent that post.

In this case, instead, it sounds like you want to work with the same document, but change its contents, using the set(...) method. Something like this:

Map<String, Object> city = new HashMap<>();
city.put("name", "Los Angeles");
city.put("state", "CA");
city.put("country", "USA");


(This example is coming from the Firestore docs -- https://firebase.google.com/docs/firestore/manage-data/add-data )

In your case, you might want a Map<String,Integer> of bird names to counts (of those birds), and do:


Later on, if you need to update a value, you COULD change the map object and call set() again, but it might be more efficient (e.g., if you had thousands of birds?) to use the update() method to update a single field in the document, instead of sending the whole document. See, later on the docs page: https://firebase.google.com/docs/firestore/manage-data/add-data#update-data

There may be other better ways of structuring the data... I would have to think about it, but this is one way that should work!

answered ago by (3.1k points)