我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
查找结果的一种方法相当于类似查询:
db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
其中i用于不区分大小写的提取数据。
我们还可以通过另一种方式获得结果:
db.collection.find({"name":/aus/})
上面将提供名称中包含aus的结果。
其他回答
>> db.car.distinct('name')
[ "honda", "tat", "tata", "tata3" ]
>> db.car.find({"name":/. *ta.* /})
类似的查询如下所示:
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]
对于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)
在Go和mgo驱动程序中:
Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)
其中结果是所查找类型的结构实例。
由于MongoDB外壳支持正则表达式,这是完全可能的。
db.users.findOne({"name" : /.*sometext.*/});
如果我们希望查询不区分大小写,可以使用“i”选项,如下所示:
db.users.findOne({"name" : /.*sometext.*/i});