0

This is rather a solution which i wanted to share, as i didn't find any such solutions that are straight forward. This solution requires 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.

  • Above code involves great amount of time complexity to the tune of `O(n^3)`. Optimize it by using text search on all fields in a mongo collection. To do a text search on all fields in a collection, you first must create text indexes on all fields. Then you can run a search with a value like this: `var cursor = db.collection().find({ $text: { $search: } });` Check this link - https://stackoverflow.com/a/35843354/2488801 – wayne May 25 '23 at 15:56

0 Answers0