我想用SQL查询一些东西,比如查询:

SELECT * FROM users  WHERE name LIKE '%m%'

如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。


当前回答

您可以在MongoDB中使用正则表达式。

例如

db.users.find({"name": /^m/})

其他回答

对于MongoDB Compass,您需要使用严格的模式语法,例如:

{ "text": { "$regex": "^Foo.*", "$options": "i" } }

(在MongoDB Compass中,使用“而不是”很重要)

您可以使用MongoDB 2.6的新功能:

db.foo.insert({desc: "This is a string with text"});
db.foo.insert({desc:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
    $text:{
        $search:"text"
    }
});

如果您想在MongoDB中进行“like”搜索,那么应该使用$regex。通过使用它,查询将是:

db.product.find({name:{$regex:/m/i}})

有关更多信息,您也可以阅读文档-$regex

对于Go驱动程序:

filter := bson.M{
    "field_name": primitive.Regex{
        Pattern: keyword,
        Options: "",
    },
}
cursor, err := GetCollection().Find(ctx, filter)

在$in查询中使用正则表达式(MongoDB文档:$in):

filter := bson.M{
    "field_name": bson.M{
        "$in": []primitive.Regex{
            {
                Pattern: keyword,
                Options: "",
            },
        }
    }
}
cursor, err := GetCollection().Find(ctx, filter)

字符串yourdb={deepakparmar,dipak,parmar}

db.getCollection('yourdb').find({"name":/^dee/})

ans deepakparmar公司

db.getCollection('yourdb').find({"name":/d/})

ans deepakparmar,迪帕克

db.getCollection('yourdb').find({"name":/mar$/})

ans deepakparmar,帕尔马