Mongodb col1+;类col2';%测试%';

Mongodb col1+;类col2';%测试%';,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,嗨,伙计们,我们可以在mongodb做类似的事情吗 col1+col2类似于“%test%” 因为我必须在具有模式的集合中搜索test的存在 collection = { "col1" : "sds" , "col2" : "est" , "col3" : ""} 试一试 在这种情况下,正则表达式/test/也应该可以工作 当然,mongo必须对所有文档进行完全扫描,因为没有使用索引的选项 如果要连接: 如果您正在尝试连接,但仍然希望使用索引,您可能至少要找到“col1”和“col2”存在的位

嗨,伙计们,我们可以在mongodb做类似的事情吗

col1+col2类似于“%test%”

因为我必须在具有模式的集合中搜索test的存在

collection = { "col1" : "sds" , "col2" : "est" , "col3" : ""}
试一试

在这种情况下,正则表达式
/test/
也应该可以工作

当然,mongo必须对所有文档进行完全扫描,因为没有使用索引的选项


如果要连接:

如果您正在尝试连接,但仍然希望使用索引,您可能至少要找到“col1”和“col2”存在的位置,因为尝试连接不存在的内容将导致可怕的错误

考虑集合,因为串联将匹配测试,所以更好一些:

{ col1: "sdst", col2: "est", col3: "abc"}
将聚合与运算符一起使用,并在中:

在初始匹配之后,仍然不能对任何内容使用索引,但这是一个优于的索引,这将扼杀任何使用索引的机会

如果您的意思是希望在“col1”和“col2”中查找“test”,那么这很简单,只需在查询中使用以查找

db.test.find({ $or: [ { col1: "test" }, { col2: "test" } ] })

或者$regex,如果您必须在字符串中找到它。请注意,如果您不是从字符串的开头查看,$regex的效率不是很高,如:“^test”

您的问题是要在col1或col2中查找“test”,还是要连接值并查找字符串
db.test.aggregate([
    // Find the rows you can concatenate -- uses index
    {$match: { col1: {$exists: true}, col2: {$exists: true}} },

    // Concatenate the strings and retain the original columns
    {$project:{
        col1: 1,
        col2: 1,
        col3: 1, 
        newcol: {$concat: [ "$col1", "$col2" ]}
    }},

    // Match the required strings in the concatenated result
    {$match: { newcol: {$regex: "test", $options: "i"} } },

    // Restore the original document fields only    
    {$project: { col1: 1, col2: 1, col3: 1 }
])
db.test.find({ $or: [ { col1: "test" }, { col2: "test" } ] })