[Firestore] Extract the collection with where condition in Ruby and delete the record

Overview

When using the Firestore API in Ruby, I summarized what to do if you want to delete only the specified collection that meets the where condition.

Assumptions, etc.

Implementation sample

sample.rb


def delete_sample
  #Get firestore object
  firestore = Google::Cloud::Firestore.new
  #For storing the doc array to be deleted
  doc_array = []
  #Get collection
  col_ref = firestore.col 'sample_collection'
  #Collection criteria
  query = col_ref.where 'category', '==', 'test'
  query.get do |r|
    #Store the target doc in an array
    doc_array.push r.ref
  end
  #Consider that you can only delete up to 500
  document_index = 0
  batch_index = 0
  #Delete in batch
  while document_index < doc_array.size
    firestore.batch do |b|
      #Suspended at 501st index
      break if batch_index == 500

      b.delete doc_array[document_index]
      document_index += 1
      batch_index += 1
    end
    batch_index = 0
  end
end

Recommended Posts

[Firestore] Extract the collection with where condition in Ruby and delete the record
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
Feel the basic type and reference type easily with ruby
About the difference between classes and instances in Ruby
Feel the basic type and reference type easily with ruby 2
[Spring Data JPA] Can And condition be used in the automatically implemented method of delete?
About the difference between "(double quotation)" and "single quotation" in Ruby
The difference between programming with Ruby classes and programming without it
Write DiscordBot to Spreadsheets Write in Ruby and run with Docker
[Learning record] I got the current time in Ruby and output a different greeting for each time.
Install gem in Serverless Framework and AWS Lambda with Ruby environment
[jOOQ] How to CASE WHEN in the WHERE / AND / OR clause
How to get and add data from Firebase Firestore in Ruby
Things to remember and concepts in the Ruby on Rails tutorial
[Ruby on Rails] How to log in with only your name and password using the gem devise
Getting Started with Doma-Using Logical Operators such as AND and OR in the WHERE Clause of the Criteria API