如何在Ruby on Rails应用的所有MongoDB数据库中全局搜索指定值?
在Ruby on Rails应用的所有MongoDB数据库中全局搜索指定值的解决方案
此方案可直接实现在Ruby on Rails应用的所有MongoDB数据库的所有集合的所有字段中搜索指定值,支持不区分大小写的全局搜索。使用前需在mongoid.yml中配置所有数据库URI,具体实现代码如下:
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
该方案通过遍历指定数据库的所有集合,逐个文档、逐个字段进行不区分大小写的匹配,找到目标值时输出对应的集合、字段和内容;搜索失败或无匹配结果时也会给出对应提示。
内容的提问来源于stack exchange,提问作者user2573178
相关产品推荐
相关产品推荐

