【问题标题】:MongoDB - Search two fields with two queriesMongoDB - 用两个查询搜索两个字段
【发布时间】:2020-04-13 19:41:08
【问题描述】:

自从我使用 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%'

我已经在这里搜索并尝试了所有解决方案,到目前为止,“位置”字段似乎是一个问题,因为它在搜索/查找时总是不返回任何内容,而在标题/描述上它工作正常。我认为我的指数是坏的什么的。我承认我对索引/更高级的搜索不太熟悉,所以我希望得到一些指导。

谢谢。

【问题讨论】:

  • 那么您是否想要 select * from where table where title='value' and location='value' 之类的东西??
  • 更好地描述您尝试执行的查询真的很有帮助,您是在尝试find a document whose title or description matches a value and location matches another value 还是什么?
  • 如果您想获得与两个查询匹配的结果,为什么要将其作为两个查询来执行?那么它基本上将是一个and 操作.find({ title: string, description: string, location: string}),如果不是,请与 req o/p 分享示例文档
  • 我添加了一个 SQL 等效查询。从一开始就应该这样做。
  • @devdrg :好的,现在我明白了。请检查我的答案..

标签: python python-3.x mongodb search indexing


【解决方案1】:

你需要试试$or

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

收藏:

/* 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"
}

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多