Catch up on highlights from Firebase at Google I/O 2023. Learn more

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

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

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

किसी दस्तावेज़ को हटाने के लिए, निम्न भाषा-विशिष्ट 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() विधि का प्रयोग करें:

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

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

जब आप किसी दस्तावेज़ को हटाते हैं, तो Cloud Firestore अपने उप-संग्रह के दस्तावेज़ों को स्वचालित रूप से नहीं हटाता है। आप अभी भी उपसंग्रह दस्तावेज़ों को संदर्भ द्वारा एक्सेस कर सकते हैं। उदाहरण के लिए, आप पथ /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() विधि का उपयोग करें:

नोट: यह उत्पाद वॉचओएस और एप क्लिप लक्ष्यों पर उपलब्ध नहीं है।
db.collection("cities").document("BJ").updateData([
    "capital": FieldValue.delete(),
]) { err in
    if let err = err {
        print("Error updating document: \(err)")
    } else {
        print("Document successfully updated")
    }
}
उद्देश्य सी

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):
    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 CLI का उपयोग कर सकते हैं। डेटा को हटाने के लिए निम्न आदेश का प्रयोग करें:

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

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

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

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

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

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

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

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

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