jeudi 25 mai 2023

Ruby Rails program to search a value in all fields of all collections from all the mongodb databases of your app

This rather my solution which i wanted to share, as i didn't any such solutions that are straight forward. This solution needs to be provided with all the database URI configured in your mongoid.yml.

uriList=['mongodb://127.0.0.1:27017/my_app_db1',
    'mongodb://127.0.0.1:27017/my_app_db2', 
    'mongodb://127.0.0.1:27017/my_app_db3', 
    'mongodb://127.0.0.1:27017/my_app_db4'
     ]

def searchDb(dbUri, search_value)
    puts "Searching in #{dbUri}++++++++++++++++++++++++++++++++++++++++++"
    client = Mongo::Client.new(dbUri)
    # List all collections in the current database
    #collections = client.database.list_collections.map(&:name)
    collections = client.database.list_collections
    # search the collection
    collections.each do |collection|
            flag=false
            begin
                puts "      searching in collection- #{collection[:name]}"
                colln=client[ collection[:name] ]
                # Iterate over the fields of each collection
            colln.find.each do |document|
                document.each do |field, value|
                        # Perform a case-insensitive search for the value
                        if value.to_s.downcase.include?(search_value.downcase)
                            flag=true
                            puts "          Collection: #{collection[:name]}"
                            puts "          Field: #{field}"
                            puts "          Value: #{value}"
                            puts "\n"
                        end
                    end
                end
        rescue
            puts "      ** failed to search in #{collection[:name]} ** "
            puts "" 
        end
        unless flag
            puts "          --not found or failed in #{collection[:name]} ** "
        end
    end
    
end

#call function 
uriList.each do |myUri|
    searchDb(myUri, 'searchValue')
end

i tried with bits pieces of code.

Aucun commentaire:

Enregistrer un commentaire