MongoDB /猫鼬-仅返回与$ text匹配的数组项

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

我有以下对象:

user: {
 _id: "xxx",
 name: "Lucas",
 items: [
  { name: "shoes", description: "nice shoes" },
  { name: "pants", description: "old pants" },
 ],
 places: [
  {name: "my house", loc: { type: "Point", coordinates: [-27, -43] }}
 ]
}

我需要执行仅返回项目的文本搜索($ text)。例如:

await User.find({ $text: { $search: "shoes" } });

这有效!但它也返回裤子,因为它不仅返回用户,而且还返回数组项。这就是问题,我需要对数据库中的项目进行分页。因此,我只需要返回与$ text搜索匹配的数组项。我知道,如果items本身就是一个集合,它将起作用,但是在我的情况下,我需要在用户内部使用它们,因为我将$ text用于项目,将$ geoWithin用于位置。

因此,如何退还用户,使其仅保留与我的$ text搜索匹配的项目?

mongodb mongoose full-text-search
1个回答
0
投票

您是否尝试使用正则表达式要将正则表达式包含在该字段的查询条件的逗号分隔列表中,请使用$ regex运算符。例如:

{ name: { $regex: /acme.*corp/i, $nin: [ 'acmeblahcorp' ] } }

或类似]

db.users.find({"name": /^m/})

https://docs.mongodb.com/manual/reference/operator/query/regex/

© www.soinside.com 2019 - 2024. All rights reserved.