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

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

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


当前回答

字符串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,帕尔马

其他回答

您已经得到了答案,但要匹配不区分大小写的正则表达式,可以使用以下查询:

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

/m/i中的i表示不区分大小写,.pretty()提供了更漂亮的输出。

在Go和mgo驱动程序中:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

其中结果是所查找类型的结构实例。

在PHP中,可以使用以下代码:

$collection->find(array('name'=> array('$regex' => 'm'));

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();

类似的查询如下所示:

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]