How to move all Firebase database records (not a specific record with an id) from a specific location to another. Code for moving certain records:
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CollectionReference addToCartRef1 = firestore.collection("AddToCart");
DocumentReference addToCartRef2 = addToCartRef1.document(auth.getCurrentUser().getUid());
CollectionReference addToCartRef3 = addToCartRef2.collection("Product");
DocumentReference fromPath = addToCartRef3.document("DiaSef1RX9xlAFm26P8M");
CollectionReference deletedAddToCartRef1 = firestore.collection("AddToPurchased");
DocumentReference deletedAddToCartRef2 = deletedAddToCartRef1.document(auth.getCurrentUser().getUid());
CollectionReference deletedAddToCartRef3 = deletedAddToCartRef2.collection("Product");
DocumentReference toPath = deletedAddToCartRef3.document("DiaSef1RX9xlAFm26P8M");
moveFirestoreDocument(fromPath, toPath);
}
});
Database structure:
,
CodePudding user response:
Firestore does not have any "move" operation for documents. What you will have to do is:
- Query for each document you want to move
- Iterate the results and copy them into new documents in the new collection
- Delete the original documents
CodePudding user response:
Method: Move data from Firestore Database (not Realtime Database) to new collection in Android Studio
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
firestore.collection("AddToCart").document(auth.getCurrentUser().getUid())
.collection("Product")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot tasks1 = task.getResult();
CollectionReference addToCartRef1 = firestore.collection("AddToCart");
DocumentReference addToCartRef2 = addToCartRef1.document(auth.getCurrentUser().getUid());
CollectionReference addToCartRef3 = addToCartRef2.collection("Product");
CollectionReference deletedAddToCartRef1 = firestore.collection("AddToPurchased");
DocumentReference deletedAddToCartRef2 = deletedAddToCartRef1.document(auth.getCurrentUser().getUid());
CollectionReference deletedAddToCartRef3 = deletedAddToCartRef2.collection("Product");
for (DocumentSnapshot doc1: tasks1.getDocuments()) {
DocumentReference fromPath = addToCartRef3.document(doc1.getReference().getId());
DocumentReference toPath = deletedAddToCartRef3.document(doc1.getReference().getId());
moveFirestoreDocument(fromPath, toPath);
}
}
}
});
}
});