我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
In
使用Python的PyMongoMongoose使用Node.jsJongo,使用Javamgo,使用Go
您可以执行以下操作:
db.users.find({'name': {'$regex': 'sometext'}})
其他回答
db.users.insert({name: 'patrick'})
db.users.insert({name: 'petra'})
db.users.insert({name: 'pedro'})
因此:
For:
db.users.find({name: /a/}) // Like '%a%'
输出:patrick,petra
For:
db.users.find({name: /^pa/}) // Like 'pa%'
输出:patrick
For:
db.users.find({name: /ro$/}) // Like '%ro'
输出:pedro
对于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)
您可以使用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"
}
});
您有两个选择:
db.users.find({"name": /string/})
or
db.users.find({"name": {"$regex": "string", "$options": "i"}})
对于第二个,您有更多的选项,如选项中的“i”,以使用不区分大小写的方式查找。
关于“字符串”,可以使用“.string.”(%string%),或“string.*”(string%)和“.*string”(%sstring)。您可以根据需要使用正则表达式。
如果您想在MongoDB中进行“like”搜索,那么应该使用$regex。通过使用它,查询将是:
db.product.find({name:{$regex:/m/i}})
有关更多信息,您也可以阅读文档-$regex