اطلاعات را از Cloud Firestore حذف کنید

مثال‌های زیر نحوه حذف اسناد، فیلدها و مجموعه‌ها را نشان می‌دهند.

اسناد را حذف کنید

برای حذف یک سند، از متدهای delete() مخصوص زبان زیر استفاده کنید:

از متد deleteDoc() استفاده کنید:

import { doc, deleteDoc } from "firebase/firestore";

await deleteDoc(doc(db, "cities", "DC"));

از متد delete() استفاده کنید:

db.collection("cities").doc("DC").delete().then(() => {
    console.log("Document successfully deleted!");
}).catch((error) => {
    console.error("Error removing document: ", error);
});

از متد delete() استفاده کنید:

توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
do {
  try await db.collection("cities").document("DC").delete()
  print("Document successfully removed!")
} catch {
  print("Error removing document: \(error)")
}

از روش deleteDocumentWithCompletion: استفاده کنید:

توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
[[[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]
    deleteDocumentWithCompletion:^(NSError * _Nullable error) {
      if (error != nil) {
        NSLog(@"Error removing document: %@", error);
      } else {
        NSLog(@"Document successfully removed!");
      }
}];

از متد delete() استفاده کنید:

db.collection("cities").document("DC")
    .delete()
    .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") }
    .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) }

از متد delete() استفاده کنید:

db.collection("cities").document("DC")
        .delete()
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "DocumentSnapshot successfully deleted!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error deleting document", e);
            }
        });

از متد delete() استفاده کنید:

db.collection("cities").doc("DC").delete().then(
      (doc) => print("Document deleted"),
      onError: (e) => print("Error updating document $e"),
    );

از متد delete() استفاده کنید:

// asynchronously delete a document
ApiFuture<WriteResult> writeResult = db.collection("cities").document("DC").delete();
// ...
System.out.println("Update time : " + writeResult.get().getUpdateTime());

از متد delete() استفاده کنید:

db.collection("cities").document("DC").delete()

از متد delete() استفاده کنید:

await db.collection("cities").document("DC").delete()

از متد Delete() استفاده کنید:

db->Collection("cities").Document("DC").Delete().OnCompletion(
    [](const Future<void>& future) {
      if (future.error() == Error::kErrorOk) {
        std::cout << "DocumentSnapshot successfully deleted!" << std::endl;
      } else {
        std::cout << "Error deleting document: " << future.error_message()
                  << std::endl;
      }
    });

از متد delete() استفاده کنید:

const res = await db.collection('cities').doc('DC').delete();

از متد Delete() استفاده کنید:


import (
	"context"
	"log"

	"cloud.google.com/go/firestore"
)

func deleteDoc(ctx context.Context, client *firestore.Client) error {
	_, err := client.Collection("cities").Doc("DC").Delete(ctx)
	if err != nil {
		// Handle any errors in an appropriate way, such as returning them.
		log.Printf("An error has occurred: %s", err)
	}

	return err
}

از متد delete() استفاده کنید:

$db->collection('samples/php/cities')->document('DC')->delete();

از متد DeleteAsync() استفاده کنید:

DocumentReference cityRef = db.Collection("cities").Document("DC");
cityRef.DeleteAsync();

از متد DeleteAsync() استفاده کنید:

DocumentReference cityRef = db.Collection("cities").Document("DC");
await cityRef.DeleteAsync();

از متد delete() استفاده کنید:

city_ref = firestore.doc "#{collection_path}/DC"
city_ref.delete

هنگامی که یک سند را حذف می کنید، Cloud Firestore به طور خودکار اسناد موجود در زیر مجموعه های خود را حذف نمی کند. همچنان می توانید با مراجعه به اسناد زیر مجموعه دسترسی داشته باشید. برای مثال، می‌توانید در مسیر /mycoll/mydoc/mysubcoll/mysubdoc به سند دسترسی داشته باشید، حتی اگر سند اجداد را در /mycoll/mydoc حذف کنید.

اسناد اجدادی که وجود ندارند در کنسول ظاهر می شوند ، اما در نتایج پرس و جو و عکس های فوری ظاهر نمی شوند.

اگر می خواهید یک سند و تمام اسناد موجود در زیر مجموعه های آن را حذف کنید، باید این کار را به صورت دستی انجام دهید. برای اطلاعات بیشتر، به حذف مجموعه ها مراجعه کنید.

حذف فیلدها

برای حذف فیلدهای خاص از یک سند، هنگام به روز رسانی یک سند، از روش های FieldValue.delete() مخصوص زبان زیر استفاده کنید:

از متد deleteField() استفاده کنید:

import { doc, updateDoc, deleteField } from "firebase/firestore";

const cityRef = doc(db, 'cities', 'BJ');

// Remove the 'capital' field from the document
await updateDoc(cityRef, {
    capital: deleteField()
});

از متد FieldValue.delete() استفاده کنید:

var cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
    capital: firebase.firestore.FieldValue.delete()
});

از متد FieldValue.delete() استفاده کنید:

توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
do {

  try await db.collection("cities").document("BJ").updateData([
    "capital": FieldValue.delete(),
  ])
  print("Document successfully updated")
} catch {
  print("Error updating document: \(error)")
}

از روش fieldValueForDelete: استفاده کنید:

توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
[[[self.db collectionWithPath:@"cities"] documentWithPath:@"BJ"] updateData:@{
  @"capital": [FIRFieldValue fieldValueForDelete]
} completion:^(NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"Error updating document: %@", error);
  } else {
    NSLog(@"Document successfully updated");
  }
}];

از متد FieldValue.delete() استفاده کنید:

val docRef = db.collection("cities").document("BJ")

// Remove the 'capital' field from the document
val updates = hashMapOf<String, Any>(
    "capital" to FieldValue.delete(),
)

docRef.update(updates).addOnCompleteListener { }

از متد FieldValue.delete() استفاده کنید:

DocumentReference docRef = db.collection("cities").document("BJ");

// Remove the 'capital' field from the document
Map<String,Object> updates = new HashMap<>();
updates.put("capital", FieldValue.delete());

docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
    // ...
    // ...

از متد FieldValue.delete() استفاده کنید:

final docRef = db.collection("cities").doc("BJ");

// Remove the 'capital' field from the document
final updates = <String, dynamic>{
  "capital": FieldValue.delete(),
};

docRef.update(updates);

از متد FieldValue.delete() استفاده کنید:

DocumentReference docRef = db.collection("cities").document("BJ");
Map<String, Object> updates = new HashMap<>();
updates.put("capital", FieldValue.delete());
// Update and delete the "capital" field in the document
ApiFuture<WriteResult> writeResult = docRef.update(updates);
System.out.println("Update time : " + writeResult.get());

از روش firestore.DELETE_FIELD استفاده کنید:

city_ref = db.collection("cities").document("BJ")
city_ref.update({"capital": firestore.DELETE_FIELD})

از روش firestore.DELETE_FIELD استفاده کنید:

city_ref = db.collection("cities").document("BJ")
await city_ref.update({"capital": firestore.DELETE_FIELD})

از متد FieldValue::Delete() استفاده کنید:

DocumentReference doc_ref = db->Collection("cities").Document("BJ");
doc_ref.Update({{"capital", FieldValue::Delete()}})
    .OnCompletion([](const Future<void>& future) { /*...*/ });

از متد FieldValue.delete() استفاده کنید:

// Create a document reference
const cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
const res = await cityRef.update({
  capital: FieldValue.delete()
});

از روش firestore.Delete استفاده کنید:


import (
	"context"
	"log"

	"cloud.google.com/go/firestore"
)

func deleteField(ctx context.Context, client *firestore.Client) error {
	_, err := client.Collection("cities").Doc("BJ").Update(ctx, []firestore.Update{
		{
			Path:  "capital",
			Value: firestore.Delete,
		},
	})
	if err != nil {
		// Handle any errors in an appropriate way, such as returning them.
		log.Printf("An error has occurred: %s", err)
	}

	// ...
	return err
}

از متد FieldValue::deleteField() استفاده کنید:

$cityRef = $db->collection('samples/php/cities')->document('BJ');
$cityRef->update([
    ['path' => 'capital', 'value' => FieldValue::deleteField()]
]);

از روش FieldValue.Delete استفاده کنید:

DocumentReference cityRef = db.Collection("cities").Document("BJ");
Dictionary<string, object> updates = new Dictionary<string, object>
{
    { "Capital", FieldValue.Delete }
};

از روش FieldValue.Delete استفاده کنید:

DocumentReference cityRef = db.Collection("cities").Document("BJ");
Dictionary<string, object> updates = new Dictionary<string, object>
{
    { "Capital", FieldValue.Delete }
};
await cityRef.UpdateAsync(updates);

از روش firestore.field_delete استفاده کنید:

city_ref = firestore.doc "#{collection_path}/BJ"
city_ref.update({ capital: firestore.field_delete })

حذف مجموعه ها

برای حذف کل مجموعه یا زیرمجموعه در Cloud Firestore ، تمام اسناد موجود در مجموعه یا زیر مجموعه را بازیابی (خواندن) کرده و آنها را حذف کنید. این فرآیند هم هزینه های خواندن و هم حذف را به همراه دارد. اگر مجموعه های بزرگتری دارید، ممکن است بخواهید اسناد را در دسته های کوچکتر حذف کنید تا از خطاهای خارج از حافظه جلوگیری کنید. این فرآیند را تا زمانی که کل مجموعه یا زیر مجموعه را حذف نکنید، تکرار کنید.

حذف یک مجموعه مستلزم هماهنگی تعداد نامحدودی از درخواست های حذف فردی است. اگر نیاز به حذف کل مجموعه دارید، این کار را فقط از یک محیط سرور قابل اعتماد انجام دهید. در حالی که امکان حذف مجموعه از یک سرویس گیرنده موبایل/وب وجود دارد، انجام این کار پیامدهای امنیتی و عملکردی منفی دارد.

تکه‌های زیر تا حدودی ساده شده‌اند و با مدیریت خطا، امنیت، حذف زیر مجموعه‌ها یا به حداکثر رساندن عملکرد سروکار ندارند. برای کسب اطلاعات بیشتر درباره یک رویکرد توصیه شده برای حذف مجموعه‌ها در تولید، به حذف مجموعه‌ها و زیر مجموعه‌ها مراجعه کنید.

// Deleting collections from a Web client is not recommended.
توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
// Deleting collections from an Apple client is not recommended.
توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
// Deleting collections from an Apple client is not recommended.
  
// Deleting collections from an Android client is not recommended.
// Deleting collections from an Android client is not recommended.

حذف مجموعه ها از مشتری توصیه نمی شود.

/**
 * Delete a collection in batches to avoid out-of-memory errors. Batch size may be tuned based on
 * document size (atmost 1MB) and application requirements.
 */
void deleteCollection(CollectionReference collection, int batchSize) {
  try {
    // retrieve a small batch of documents to avoid out-of-memory errors
    ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
    int deleted = 0;
    // future.get() blocks on document retrieval
    List<QueryDocumentSnapshot> documents = future.get().getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      document.getReference().delete();
      ++deleted;
    }
    if (deleted >= batchSize) {
      // retrieve and delete another batch
      deleteCollection(collection, batchSize);
    }
  } catch (Exception e) {
    System.err.println("Error deleting collection : " + e.getMessage());
  }
}
def delete_collection(coll_ref, batch_size):
    if batch_size == 0:
        return

    docs = coll_ref.list_documents(page_size=batch_size)
    deleted = 0

    for doc in docs:
        print(f"Deleting doc {doc.id} => {doc.get().to_dict()}")
        doc.delete()
        deleted = deleted + 1

    if deleted >= batch_size:
        return delete_collection(coll_ref, batch_size)
async def delete_collection(coll_ref, batch_size):
    docs = coll_ref.limit(batch_size).stream()
    deleted = 0

    async for doc in docs:
        print(f"Deleting doc {doc.id} => {doc.to_dict()}")
        await doc.reference.delete()
        deleted = deleted + 1

    if deleted >= batch_size:
        return delete_collection(coll_ref, batch_size)
// This is not supported. Delete data using CLI as discussed below.
  
async function deleteCollection(db, collectionPath, batchSize) {
  const collectionRef = db.collection(collectionPath);
  const query = collectionRef.orderBy('__name__').limit(batchSize);

  return new Promise((resolve, reject) => {
    deleteQueryBatch(db, query, resolve).catch(reject);
  });
}

async function deleteQueryBatch(db, query, resolve) {
  const snapshot = await query.get();

  const batchSize = snapshot.size;
  if (batchSize === 0) {
    // When there are no documents left, we are done
    resolve();
    return;
  }

  // Delete documents in a batch
  const batch = db.batch();
  snapshot.docs.forEach((doc) => {
    batch.delete(doc.ref);
  });
  await batch.commit();

  // Recurse on the next process tick, to avoid
  // exploding the stack.
  process.nextTick(() => {
    deleteQueryBatch(db, query, resolve);
  });
}

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/firestore"
	"google.golang.org/api/iterator"
)

func deleteCollection(w io.Writer, projectID, collectionName string,
	batchSize int) error {

	// Instantiate a client
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		return err
	}

	col := client.Collection(collectionName)
	bulkwriter := client.BulkWriter(ctx)

	for {
		// Get a batch of documents
		iter := col.Limit(batchSize).Documents(ctx)
		numDeleted := 0

		// Iterate through the documents, adding
		// a delete operation for each one to the BulkWriter.
		for {
			doc, err := iter.Next()
			if err == iterator.Done {
				break
			}
			if err != nil {
				return err
			}

			bulkwriter.Delete(doc.Ref)
			numDeleted++
		}

		// If there are no documents to delete,
		// the process is over.
		if numDeleted == 0 {
			bulkwriter.End()
			break
		}

		bulkwriter.Flush()
	}
	fmt.Fprintf(w, "Deleted collection \"%s\"", collectionName)
	return nil
}
function data_delete_collection(string $projectId, string $collectionName, int $batchSize)
{
    // Create the Cloud Firestore client
    $db = new FirestoreClient([
        'projectId' => $projectId,
    ]);
    $collectionReference = $db->collection($collectionName);
    $documents = $collectionReference->limit($batchSize)->documents();
    while (!$documents->isEmpty()) {
        foreach ($documents as $document) {
            printf('Deleting document %s' . PHP_EOL, $document->id());
            $document->reference()->delete();
        }
        $documents = $collectionReference->limit($batchSize)->documents();
    }
}
// This is not supported. Delete data using CLI as discussed below.
private static async Task DeleteCollection(CollectionReference collectionReference, int batchSize)
{
    QuerySnapshot snapshot = await collectionReference.Limit(batchSize).GetSnapshotAsync();
    IReadOnlyList<DocumentSnapshot> documents = snapshot.Documents;
    while (documents.Count > 0)
    {
        foreach (DocumentSnapshot document in documents)
        {
            Console.WriteLine("Deleting document {0}", document.Id);
            await document.Reference.DeleteAsync();
        }
        snapshot = await collectionReference.Limit(batchSize).GetSnapshotAsync();
        documents = snapshot.Documents;
    }
    Console.WriteLine("Finished deleting all documents from the collection.");
}
cities_ref = firestore.col collection_path
query      = cities_ref

query.get do |document_snapshot|
  puts "Deleting document #{document_snapshot.document_id}."
  document_ref = document_snapshot.ref
  document_ref.delete
end

با Firebase CLI داده ها را حذف کنید

همچنین می توانید از Firebase CLI برای حذف اسناد و مجموعه ها استفاده کنید. برای حذف اطلاعات از دستور زیر استفاده کنید:

firebase firestore:delete [options] <<path>>

اطلاعات را با کنسول حذف کنید

می‌توانید اسناد و مجموعه‌ها را از صفحه Cloud Firestore در کنسول حذف کنید . با حذف یک سند از کنسول، تمام داده های تودرتو در آن سند، از جمله هر مجموعه فرعی، حذف می شود.

حذف داده ها با خط مشی های TTL

یک خط مشی TTL یک فیلد معین را به عنوان زمان انقضای اسناد در یک گروه مجموعه معین تعیین می کند. عملیات حذف TTL در هزینه های حذف سند شما حساب می شود.

برای اطلاعات در مورد تنظیم TTL، به مدیریت حفظ داده با خط‌مشی‌های TTL مراجعه کنید.

برای اطلاعات بیشتر در مورد کدهای خطا و نحوه حل مشکلات تاخیر هنگام حذف داده ها ، صفحه عیب یابی را بررسی کنید.

داده ها را با Dataflow حذف کنید

Dataflow یک ابزار عالی برای عملیات انبوه در پایگاه داده Firestore شما است. رابط Firestore برای پست وبلاگ معرفی Dataflow مثالی از حذف تمام اسناد در یک گروه مجموعه دارد.

از حذف انبوه مدیریت شده استفاده کنید

Cloud Firestore از حذف انبوه یک یا چند گروه مجموعه پشتیبانی می کند. برای اطلاعات بیشتر، به حذف انبوه داده ها مراجعه کنید.