How to retrieve all data from a subcollection of all document - firebase

I am using Flutter for my app. I want to retrieve all document (not only for one user) of a subcollection and display in the app. Each user has a subcollection of Baggage and a subcollection of Car.
This is how I store in Firebase:
String createAt = DateTime.now().millisecondsSinceEpoch.toString();
var ref = FirebaseFirestore.instance.collection('Trips').doc('userId').collection('Baggage').doc(createAt);
FirebaseFirestore.instance.runTransaction((transaction) async {transaction.set(ref, {
'departure': city1.text,
'destination': city2.text,
'weight': _weightcontroller.text,
'id': userId,
'departureDate': date.text,
'username': firstname,
"timestamp": createAt,
});
});
var ref1 = FirebaseFirestore.instance
.collection('Trips')
.doc('userId')
.collection('Cars')
.doc(createAt);
How to retrieve data from subcollection 'Baggage' for all users. If there is best way so structure these data and retrieve easily, please let me know.

Firestore has something called collectionGroup query where you can get all subcollections if they have same collection name. Which can be done as
FirebaseFirestore.instance.collectionGroup('Baggage').get();
This will give you all the documents across all rooms. For reference documentation

Related

get data from both collection and it is sub collection in firestore with flutter

i have this database structure in Firestore:
this what inside places
how can i make a query in flutter to get all data inside Places sub-collection along with name from User collection, this code to get all places sub-collection data from every User collection :
Future<List<PlaceModel>> getPlaces() async {
List<PlaceModel> placesList = [];
// get all docs from user collection
var users = await udb.get();
for( var uid in users.docs) {
var userData = await udb.doc(uid.id).get();
var userPlaces = await udb.doc(uid.id).collection(placeTable).get();
userPlaces.docs.forEach((place) {
placesList.add(PlaceModel.fromMap(place.data()));
});
}
return placesList;
}
You can also use where() or orderby() methods to get data with some rules.
Firestore.instance
.collection("users")
.document(uid.id)
.collection(placeTable)
.where('fieldName', isEqualTo:name )
.snapshots()
A single query can only access a single collection, or a group of collection that have the same name. Firestore queries are shallow and don't read data from subcollections. If you need the data from the subcollection, you will have to execute an additional query to read it.

How to get data from subcollection in firestore using flutter?

i tried this .Sorry im a beginner.i cant put a document I'd in the unique I'd place as there are multiple documents under which userProducts collection comes. moreover new documents will keep generating as users increase.Inside every new document generated there's a subcollection created called userProducts.Is any other way ?
Future getProducts() async {
var firestore = Firestore.instance;
QuerySnapshot snapshot = await firestore.collection('products'). documents (doc id).collection('userProducts').getDocuments();
// .orderBy('timestamp', descending: true)
return snapshot.documents;

Firestore Update Sub-Collection Document

I would like to update a sub-collection document that I got by sending a group-query with Flutter. To my current understanding with a group-query I do not really know the parent of a sub-collection.
In order to do so, I need the document id of the parent document. The update query would then look like the following:
collection(collectionName)
.document(parentDocumentId)
.collection(subCollectionName)
.document(subCollectionDocumentId)
.updateData(someMapWithData);
Is it necessary to save the parentDocumentId within the sub-collection document to be able to do such update or is there another way to do so?
If you want to update a document inside a subcollection, then you need both the top document id and the document id inside the subcollection.
Is it necessary to save the parentDocumentId within the sub-collection document to be able to do such update or is there another way to do so?
No, its not necessary, but if you have the parentDocumentId, and you dont have the subDocumentId, then you need to query to retrieve it:
Firestore.instance
.collection("path")
.document("docPath")
.collection("subCollection")
.where("name", isEqualTo: "john")
.getDocuments()
.then((res) {
res.documents.forEach((result) {
Firestore.instance
.collection("path")
.document("docPath")
.collection("subCollection")
.document(result.documentID)
.updateData({"name": "martin"});
});
});
Unfortunately, I couldn't find an option to do this more cost-efficient. With this method, you have 1 read and 1 write operation.
Code for the following storage structure: users/${uid}/collection/$documentName/
static Future updateSubData(String uid, String mainCollection,
String subCollection, Map<String, dynamic> json) async {
//get document ID
final querySnapshot = await fireStoreInstance
.collection(mainCollection)
.doc(uid)
.collection(subCollection)
.limit(1)
.get();
//document at position 0
final documentId = querySnapshot.docs[0].id;
//update this document
await fireStoreInstance
.collection(mainCollection)
.doc(uid)
.collection(subCollection)
.doc(documentId)
.update(json);
}
I case you have more documents in the subcollection you need to remove .limit(1) so you get all documents.

How to add Collection To Document Firestore

I have a User collection in my Firstore database, and I want to imbed a Workout collection in each document of my User collection. I can do this on the Cloud Firestore Dashboard, but how can I do this when I create a new User document in my Flutter code?
My normal code for adding a user looks like this:
Firestore.instance.runTransaction((transaction) async {
await transaction
.set(Firestore.instance.collection('users').document(uuid_), {
'grade': _grade,
'name': _name,
});
});
but I want to somehow add a Workout subcollection to my newly created User document. Thanks for any help
There is no public API to create a new subcollection. Instead a collection is created automatically when you add the first document to it.
So something like:
transaction.set(
Firestore.instance.
collection('users').document(uuid_).
collection("workouts").document("workoutid"), {
'grade': _grade,
'name': _name,
});

FLUTTER | How to add data to an existing document in firestore

I'm using firestore to store data of my flutter application, and I made a function that creates a document in firestore automatically after the user login
Now I want the user when he fills this form , the data will be added in the same document where the user's email exists.
RaisedButton(
child: Text("Submit"),
onPressed: () {
final CollectionReference users = Firestore.instance.collection('users');
Firestore.instance
.runTransaction((Transaction transaction) async {
CollectionReference reference =
Firestore.instance.collection('users');
await reference
.add({"fullname": nameController.text, "PhoneNumber": phoneController.text, "adresse": adressController.text});
nameController.clear();
phoneController.clear();
adressController.clear();
});}
I tried this code but it adds new document.
Specify document name before updating database.
Firestore.instance
.collection('Products')
.document('Apple')
.updateData({
'price': 120,
'quantity': 15
});
Here my price and quantity data are numbers. If yours are Strings put String values there.
Best practice is to use transaction.
Make sure that document reference is a reference to a file that you wish to update.
Firestore.instance.runTransaction((transaction) async {
await transaction.update(
documentReference, data);
};
It will make sure that update happens in order in case there are many clients doing it.
In the case of a concurrent edit, Cloud Firestore runs the entire transaction again. For example, if a transaction reads documents and another client modifies any of those documents, Cloud Firestore retries the transaction. This feature ensures that the transaction runs on up-to-date and consistent data.
More info here
Try .setData({"fullname": nameController.text, "PhoneNumber": phoneController.text, "adresse": adressController.text}, merge: true).
Update 2021:
You need to update the data to add it to an existing document.
var collection = FirebaseFirestore.instance.collection('users');
collection
.doc('doc_id') // <-- Doc ID where data should be updated.
.update({'age' : 20}) // <-- New data
.then((_) => print('Updated'))
.catchError((error) => print('Update failed: $error'));

Resources