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

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

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


当前回答

使用JavaScript RegExp

按空格拆分名称字符串,并生成单词数组映射到迭代循环,并将字符串转换为名称中每个单词的正则表达式

let name=“My name”.split(“”).map(n=>新RegExp(n));console.log(名称);

结果:

[/My/, /Name/]

有两种情况可以匹配字符串,

$in:(类似于$or条件)

尝试在表达式中使用$。要在$in查询表达式中包含正则表达式,只能使用JavaScript正则表达式对象(即/patter/)。例如:

db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]

$all:(类似于$和条件)文档应包含所有单词

db.users.find({ name: { $all: name } }); // name = [/My/, /Name/]

使用嵌套的$and和$or条件和$regex

有两种情况可以匹配字符串,

$或:(类似于$in条件)

db.users.find({
  $or: [
    { name: { $regex: "My" } },
    { name: { $regex: "Name" } }
    // if you have multiple fields for search then repeat same block
  ]
})

游戏场

$和:(类似于$all条件)文档应包含所有单词

db.users.find({
  $and: [
    {
      $and: [
        { name: { $regex: "My" } },
        { name: { $regex: "Name" } }
      ]
    }
    // if you have multiple fields for search then repeat same block
  ]
})

游戏场

其他回答

使用聚合子字符串搜索(带索引!!!):

db.collection.aggregate([{
        $project : {
            fieldExists : {
                $indexOfBytes : ['$field', 'string']
            }
        }
    }, {
        $match : {
            fieldExists : {
                $gt : -1
            }
        }
    }, {
        $limit : 5
    }
]);

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

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

使用JavaScript RegExp

按空格拆分名称字符串,并生成单词数组映射到迭代循环,并将字符串转换为名称中每个单词的正则表达式

let name=“My name”.split(“”).map(n=>新RegExp(n));console.log(名称);

结果:

[/My/, /Name/]

有两种情况可以匹配字符串,

$in:(类似于$or条件)

尝试在表达式中使用$。要在$in查询表达式中包含正则表达式,只能使用JavaScript正则表达式对象(即/patter/)。例如:

db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]

$all:(类似于$和条件)文档应包含所有单词

db.users.find({ name: { $all: name } }); // name = [/My/, /Name/]

使用嵌套的$and和$or条件和$regex

有两种情况可以匹配字符串,

$或:(类似于$in条件)

db.users.find({
  $or: [
    { name: { $regex: "My" } },
    { name: { $regex: "Name" } }
    // if you have multiple fields for search then repeat same block
  ]
})

游戏场

$和:(类似于$all条件)文档应包含所有单词

db.users.find({
  $and: [
    {
      $and: [
        { name: { $regex: "My" } },
        { name: { $regex: "Name" } }
      ]
    }
    // if you have multiple fields for search then repeat same block
  ]
})

游戏场

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

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