我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
您可以使用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.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);
对于Scala ReactiveMongo API,
val query = BSONDocument("title" -> BSONRegex(".*" + name + ".*", "")) // like
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]
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)
在PHP中,可以使用以下代码:
$collection->find(array('name'=> array('$regex' => 'm'));
有多种方法可以实现这一点。
最简单的一个:
db.users.find({"name": /m/})
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
db.users.find({ "name": { $regex: "m"} })
更多详细信息可以在$regex中找到。