【问题标题】:Return documents filtered by column after $text search在 $text 搜索后返回按列过滤的文档
【发布时间】:2021-10-09 22:16:57
【问题描述】:

我正在对我的集合进行 $text 搜索,其中我制作了复合文本索引。我正在做的是一种解决方法(我认为)我无法以其他方式实现。我最初想要的是在用户给出的字段(列)上进行 $text 搜索。但我想这是不可能的,因为它们大约有 4 个文本字段,我猜 mongodb 不能那样工作。 所以现在,我要做的是搜索所有字段,然后过滤掉用户指定列中搜索关键字匹配的文档。

我已经编码直到全文搜索,但我不知道如何做文档过滤器的事情。有可能吗?

我的指数:Details.collection.createIndex({ name: 'text', desc: 'text', bio: 'text'})

收集文件:

{ "name" : "kat saphire",    "desc" : "I guess that's how it works",  "bio": "Creating a life, I love"}
{ "name" : "john doe",    "desc" : "I practice what I post", "bio": "Simplicity is the key to happiness"}
{ "name" : "kat lisa",    "desc" : "to be or not to be",   "bio": "In a world of worriers, be a warrior"}
{ "name" : "david beckham",  "desc" : "Live as if you were to die tomorrow",   "bio": "I practice what I post"}
{ "name" : "aura leo",    "desc" : "That which does not kill us makes us stronger", "bio": "She turned her can't into can and her dreams into plans"}

我的关键字搜索:practice what I post

全文搜索结果:

{ "name" : "john doe",    "desc" : "I practice what I post", "bio": "Simplicity is the key to happiness"}
{ "name" : "david beckham",  "desc" : "Live as if you were to die tomorrow",   "bio": "I practice what I post"}

现在我只想要一列的结果,例如“desc”

所以我想要的输出应该有:

{ "name" : "john doe",    "desc" : "I practice what I post", "bio": "Simplicity is the key to happiness"}

到目前为止,我使用聚合来获得我的结果。

【问题讨论】:

  • 你想完成什么? $text 也不是正确的,或者 mongo 不是正确的工具。
  • 你的意思是我认为只有 1 个文件,$limit 我猜
  • 我想使用 $text 搜索用户在集合的列(字段)中输入的任何内容。

标签: node.js mongodb mongoose


【解决方案1】:

你可以这样做:

const regex = { $regex: `${searchWord}`, $options: 'i' }
await db.collectionName.aggregate([{$match: { desc: regex }}])[0]

【讨论】:

  • 你能解释一下最后的[0]吗?正则表达式在这里也不会很慢吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 2018-04-13
  • 2017-12-08
  • 1970-01-01
相关资源
最近更新 更多