You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 21:32:42