我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
正则表达式的处理成本很高。
另一种方法是创建文本索引,然后使用$search进行搜索。
创建要搜索的字段的文本索引:
db.collection.createIndex({name: 'text', otherField: 'text'});
在文本索引中搜索字符串:
db.collection.find({
'$text'=>{'$search': "The string"}
})
其他回答
In
使用Python的PyMongoMongoose使用Node.jsJongo,使用Javamgo,使用Go
您可以执行以下操作:
db.users.find({'name': {'$regex': 'sometext'}})
FullName类似于“last”,两个日期之间的状态==“结束”:
db.orders.find({
createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
$lt:ISODate("2017-05-05T10:08:16.111Z")},
status:"Pending",
fullName:/last/}).pretty();
status==“待定”,orderId LIKE“PHA871674”:
db.orders.find({
status:"Pending",
orderId:/PHA876174/
}).pretty();
在SQL中,“like”查询如下所示:
select * from users where name like '%m%'
在MongoDB控制台中,如下所示:
db.users.find({"name": /m/}) // Not JSON formatted
db.users.find({"name": /m/}).pretty() // JSON formatted
此外,pretty()方法将在所有地方生成一个格式化的JSON结构,这样可读性更强。
您有两个选择:
db.users.find({"name": /string/})
or
db.users.find({"name": {"$regex": "string", "$options": "i"}})
对于第二个,您有更多的选项,如选项中的“i”,以使用不区分大小写的方式查找。
关于“字符串”,可以使用“.string.”(%string%),或“string.*”(string%)和“.*string”(%sstring)。您可以根据需要使用正则表达式。
Use:
db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()
当我们搜索字符串模式时,最好使用上面的模式,因为我们不确定大小写。