क्लाउड फायरस्टोर से डेटा हटाएं

निम्नलिखित उदाहरण दर्शाते हैं कि दस्तावेज़, फ़ील्ड और संग्रह को कैसे हटाया जाए।

दस्तावेज़ हटाएँ

किसी दस्तावेज़ को हटाने के लिए, निम्नलिखित भाषा-विशिष्ट delete() विधियों का उपयोग करें:

Web modular API

deleteDoc() विधि का उपयोग करें:

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

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

Web namespaced API

delete() विधि का उपयोग करें:

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

delete() विधि का उपयोग करें:

नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
do {
  try await db.collection("cities").document("DC").delete()
  print("Document successfully removed!")
} catch {
  print("Error removing document: \(error)")
}
उद्देश्य सी

deleteDocumentWithCompletion: विधि का उपयोग करें:

नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
[[[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]
    deleteDocumentWithCompletion:^(NSError * _Nullable error) {
      if (error != nil) {
        NSLog(@"Error removing document: %@", error);
      } else {
        NSLog(@"Document successfully removed!");
      }
}];

Kotlin+KTX

delete() विधि का उपयोग करें:

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

Java

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);
            }
        });

Dart

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()

Python

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

जब आप कोई दस्तावेज़ हटाते हैं, तो क्लाउड फायरस्टोर अपने उपसंग्रहों में दस्तावेज़ों को स्वचालित रूप से नहीं हटाता है। आप अभी भी संदर्भ द्वारा उपसंग्रह दस्तावेजों तक पहुंच सकते हैं। उदाहरण के लिए, आप दस्तावेज़ को पथ /mycoll/mydoc/mysubcoll/mysubdoc पर एक्सेस कर सकते हैं, भले ही आप /mycoll/mydoc पर पूर्वज दस्तावेज़ को हटा दें।

गैर-मौजूद पूर्वज दस्तावेज़ कंसोल में दिखाई देते हैं , लेकिन वे क्वेरी परिणामों और स्नैपशॉट में दिखाई नहीं देते हैं।

यदि आप किसी दस्तावेज़ और उसके उपसंग्रहों के सभी दस्तावेज़ों को हटाना चाहते हैं, तो आपको ऐसा मैन्युअल रूप से करना होगा। अधिक जानकारी के लिए, संग्रह हटाएं देखें।

फ़ील्ड हटाएं

किसी दस्तावेज़ से विशिष्ट फ़ील्ड हटाने के लिए, दस्तावेज़ को अपडेट करते समय निम्नलिखित भाषा-विशिष्ट FieldValue.delete() विधियों का उपयोग करें:

Web modular API

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()
});

Web namespaced API

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() विधि का उपयोग करें:

नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
do {

  try await db.collection("cities").document("BJ").updateData([
    "capital": FieldValue.delete(),
  ])
  print("Document successfully updated")
} catch {
  print("Error updating document: \(error)")
}
उद्देश्य सी

fieldValueForDelete: विधि का उपयोग करें:

नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
[[[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");
  }
}];

Kotlin+KTX

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 { }

Java

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>() {
    // ...
    // ...

Dart

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})

Python

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 })

संग्रह हटाएँ

क्लाउड फायरस्टोर में संपूर्ण संग्रह या उपसंग्रह को हटाने के लिए, संग्रह या उपसंग्रह के भीतर सभी दस्तावेज़ों को पुनः प्राप्त करें (पढ़ें) और उन्हें हटा दें। इस प्रक्रिया में पढ़ने और हटाने दोनों की लागत आती है। यदि आपके पास बड़े संग्रह हैं, तो आप आउट-ऑफ-मेमोरी त्रुटियों से बचने के लिए दस्तावेज़ों को छोटे बैचों में हटाना चाह सकते हैं। प्रक्रिया को तब तक दोहराएँ जब तक कि आप संपूर्ण संग्रह या उपसंग्रह को हटा न दें।

किसी संग्रह को हटाने के लिए अलग-अलग डिलीट अनुरोधों की असीमित संख्या के समन्वय की आवश्यकता होती है। यदि आपको संपूर्ण संग्रह हटाने की आवश्यकता है, तो ऐसा केवल विश्वसनीय सर्वर वातावरण से ही करें। हालाँकि मोबाइल/वेब क्लाइंट से किसी संग्रह को हटाना संभव है, लेकिन ऐसा करने से सुरक्षा और प्रदर्शन पर नकारात्मक प्रभाव पड़ता है।

नीचे दिए गए स्निपेट कुछ हद तक सरल हैं और त्रुटि प्रबंधन, सुरक्षा, उपसंग्रहों को हटाने या प्रदर्शन को अधिकतम करने से संबंधित नहीं हैं। उत्पादन में संग्रहों को हटाने के लिए एक अनुशंसित दृष्टिकोण के बारे में अधिक जानने के लिए, संग्रह और उपसंग्रह हटाना देखें।

वेब
// Deleting collections from a Web client is not recommended.
तीव्र
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
// Deleting collections from an Apple client is not recommended.
उद्देश्य सी
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
// Deleting collections from an Apple client is not recommended.
  

Kotlin+KTX

// Deleting collections from an Android client is not recommended.

Java

// Deleting collections from an Android client is not recommended.

Dart

क्लाइंट से संग्रह हटाने की अनुशंसा नहीं की जाती है।

जावा
/**
 * 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)

Python

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 firestore:delete [options] <<path>>

कंसोल से डेटा हटाएं

आप कंसोल में क्लाउड फायरस्टोर पेज से दस्तावेज़ और संग्रह हटा सकते हैं। कंसोल से किसी दस्तावेज़ को हटाने से उस दस्तावेज़ में सभी नेस्टेड डेटा हटा दिए जाते हैं, जिसमें कोई भी उपसंग्रह भी शामिल है।

टीटीएल नीतियों के साथ डेटा हटाएं

टीटीएल नीति किसी दिए गए संग्रह समूह में दस्तावेज़ों के लिए समाप्ति समय के रूप में किसी दिए गए फ़ील्ड को निर्दिष्ट करती है। टीटीएल डिलीट ऑपरेशंस की गणना आपके दस्तावेज़ डिलीट लागतों में की जाती है।

टीटीएल सेट करने के बारे में जानकारी के लिए, टीटीएल नीतियों के साथ डेटा प्रतिधारण प्रबंधित करें देखें।

त्रुटि कोड पर अधिक जानकारी और डेटा हटाते समय विलंबता समस्याओं को हल करने के तरीके के लिए समस्या निवारण पृष्ठ देखें।

डेटाफ़्लो के साथ डेटा हटाएं

डेटाफ्लो आपके फायरस्टोर डेटाबेस पर बड़े पैमाने पर संचालन के लिए एक बेहतरीन उपकरण है। डेटाफ्लो परिचय ब्लॉग पोस्ट के लिए फायरस्टोर कनेक्टर में संग्रह समूह में सभी दस्तावेज़ों को हटाने का एक उदाहरण है।