在 MongoDB 中使用 $and 的多个 $regex [英] Multiple $regex using $and in MongoDB

查看:63
本文介绍了在 MongoDB 中使用 $and 的多个 $regex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些包含下一个记录的集合:

I have some collection with the next records:

{
    "_id" : ObjectId("52b18fb2a21351b2bb29dfc7"),
    "title" : "aaa"
}
{
    "_id" : ObjectId("52b18fd0d17d7f69e078f7b7"),
    "title" : "bbb"
}
{
    "_id" : ObjectId("52b18fd3d17d7f69e078f7b8"),
    "title" : "ccc"
}

下一个查询的结果是我们预期的 1 条记录(标题为aaa"):

Next query gives as a result 1 records (with title="aaa") as we expected:

db.test.find({
     {title:{$regex:'aaa'}}
})

但是当我们对 $ 使用复杂条件时,我们得到了一些意想不到的东西:

But when we use complex condition for $and we got something unexpected:

db.test.find({
    $and: [
        {title:{$regex:'aaa'}},
        {title:{$regex:'bbb'}}
    ]
})

在这种情况下,我需要完全查询,因为我将使用带有停用词的选择,例如:

I need query exactly in this case because I'm going to use selection with stop-words, for example:

db.test.find({
    $and: [
        {title:{$regex:'aaa'}},
        {title:{$regex:'bbb'}},
        {title:{$not:/bbb/i}},
    ]
})

使用上面的查询,我期望结果中只有一个字段(title="aaa").

Using query that above, I expecting only one field in result (with title="aaa").

我知道如何使用聚合解决这个问题,但我希望有另一种方法来解决它.

I have idea how to solve this issue using aggregate, but I hope there is another way how to solve it.

谢谢!

推荐答案

只需构建合适的正则表达式

Simply build proper regex

pattern "/A AND B/"
pattern "/NOT (NOT A OR NOT B)/"

正则表达式:

"/^(^A|^B)/"

或者这个

/(?=.*word1)(?=.*word2)/

这篇关于在 MongoDB 中使用 $and 的多个 $regex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆