You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCord Discord经济机器人:如何通过模糊名称在MongoDB查找商品对象

解决MongoDB数组字段的模糊搜索问题

问题根源

你的代码直接对Shop.Items数组字段使用$regex,但MongoDB针对数组元素的模糊匹配需要特定语法,且默认正则是大小写敏感的,这两点都会导致匹配失败。

修正方案

1. 正确匹配数组内元素

因为Shop.Items是数组类型,要匹配数组中包含指定关键词的元素,可采用以下两种写法,同时添加$options: "i"忽略大小写:

写法一:直接在数组字段应用正则(推荐)

search = await economy_db.find_one(
    {"_id": ctx.guild.id, "Shop.Items": {"$regex": "item", "$options": "i"}}
)

这种写法会自动遍历数组内所有元素,只要有元素匹配正则就会返回对应文档。

写法二:用$elemMatch明确指定匹配规则

search = await economy_db.find_one(
    {"_id": ctx.guild.id, "Shop.Items": {"$elemMatch": {"$regex": "item", "$options": "i"}}}
)

$elemMatch用于明确匹配数组中满足条件的元素,适合更复杂的匹配场景。

2. 提取仅匹配的商品元素

如果需要从返回的文档中只获取匹配的商品(而非整个文档),可以通过投影过滤数组:

search = await economy_db.find_one(
    {"_id": ctx.guild.id, "Shop.Items": {"$regex": "item", "$options": "i"}},
    {"Shop.Items": {"$elemMatch": {"$regex": "item", "$options": "i"}}}
)

此时search["Shop"]["Items"]只会包含匹配的商品,方便后续展示选择列表。

3. 特殊场景处理

若Shop.Items中的元素是嵌套对象(比如每个商品包含name字段),需要调整匹配路径:

search = await economy_db.find_one(
    {"_id": ctx.guild.id, "Shop.Items.name": {"$regex": "item", "$options": "i"}}
)

内容的提问来源于stack exchange,提问作者Feor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:25:16