MongoDB-使用两个查询搜索两个字段

问题描述 投票:0回答:2

自从我和mongo合作以来已经有一段时间了,我觉得我已经失去了这个。

我在一个集合中有一系列文档,格式为:

{
  _id,
  title: string,
  description: string,
  location: string
  ...
}

而且我想通过两个查询来搜索那些文档:

第一个查询-搜索标题和说明,第二次查询-在位置搜索

它应该只返回与两个查询都匹配的结果。

或SQL等效项:

SELECT *
FROM `docs`
WHERE (`title` LIKE '%query_ONE%' OR `description` LIKE '%query_ONE%')
AND `city` LIKE '%query_TWO%'

我已经在这里搜索并尝试了每种解决方案,到目前为止,“位置”字段似乎是一个问题,因为它始终在搜索/查找中不返回任何内容,而在标题/描述中则可以正常工作。我认为我的索引不好。我承认我不太熟悉索引编制/更高级的搜索,因此我希望对此有所指导。

谢谢。

python python-3.x mongodb search indexing
2个回答

0
投票

您需要尝试$or

db.docs.find({$or:[{title:'title'}, {description:'des'}], location:'my'})

Collection:

/* 1 */
{
    "_id" : ObjectId("5dfeac7b400289966e2042c7"),
    "title" : "title",
    "description" : "des",
    "location" : "my"
}

/* 2 */
{
    "_id" : ObjectId("5dfeac84400289966e204380"),
    "title" : "title1",
    "description" : "des1",
    "location" : "my"
}

/* 3 */
{
    "_id" : ObjectId("5dfeac8b400289966e2043ec"),
    "title" : "title",
    "description" : "des",
    "location" : "my1"
}

/* 4 */
{
    "_id" : ObjectId("5dfead06400289966e204e1e"),
    "title" : "title1",
    "description" : "des1",
    "location" : "my1"
}

/* 5 */
{
    "_id" : ObjectId("5dfeae24400289966e2067ad"),
    "title" : "title",
    "description" : "des1",
    "location" : "my"
}

/* 6 */
{
    "_id" : ObjectId("5dfeae2f400289966e206894"),
    "title" : "title1",
    "description" : "des",
    "location" : "my"
}

结果:

/* 1 */
{
    "_id" : ObjectId("5dfeac7b400289966e2042c7"),
    "title" : "title",
    "description" : "des",
    "location" : "my"
}

/* 2 */
{
    "_id" : ObjectId("5dfeae24400289966e2067ad"),
    "title" : "title",
    "description" : "des1",
    "location" : "my"
}

/* 3 */
{
    "_id" : ObjectId("5dfeae2f400289966e206894"),
    "title" : "title1",
    "description" : "des",
    "location" : "my"
}
© www.soinside.com 2019 - 2024. All rights reserved.