mongodb - 我如何在 mongodb 的数组中找到文本搜索

标签 mongodb mongodb-query

 {
    "_id":objectId(23651478),
    "name":"Tomatos"
    "array":[
             {"title":"Vegetables"}
            ]
    "description":"Vegitables are good to health"
 },
 {
    "_id":objectId(45761244),
    "name":"Apples"
    "array":[
             {"title":"Fruits"}
            ]
    "description":"Fruits are good to health, vegitables are also good to health"
 },
 {
    "_id":objectId(45761244),
    "name":"Apples"
    "array":[
             {"title":"Vegetables-home-made"}
            ]
    "description":"Fruits are good to health, vegitables are also good to health"
 }

以上是我的项目要求的 mongo 模式模式。当我只想搜索蔬菜时,必须要有蔬菜名称。如果我同时搜索蔬菜和水果,则必须同时搜索两个名称,即 Tomato 和 Apple。

我这样使用 "$in" 运算符

{"array":{$in:[{"title":"Vegetables"},{"title":"Fruits"}]}}

它只给出标题为Vegetables 的文档,而不是Vegetables-Home-made。为此,我尝试使用 $elemMatch

 {"array":{$elemMatch:[{"title":"Vegetables"},{"title":"Fruits"}]}}

但是当我们在 elemMatch 中搜索倍数,即 VegetablesFruits 时,它给出了错误,我想在数组中搜索特定标题键的文本只是,

{"array":{$text:{:$search:[{"title":"Vegetables"},{"title":"Fruits"}]}}}

最佳答案

这是你想要的:

您可以像这样在 $in 运算符中使用正则表达式:

{array: { $elemMatch: { title: { $in: [/Vegetables/, /Fruits/] }}}}

关于mongodb - 我如何在 mongodb 的数组中找到文本搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39996979/

相关文章:

mongodb - 如何从字符串转换为日期数据类型?

mongodb - 如何在 mongoDB 中使用 findOne 获取此查询形式的嵌套数组

mongodb - 大量集合的聚合管道缓慢

java - 如何通过Java代码为mongoDB实现嵌套查询

MongoDB 聚合文档返回计数或 0

MongoDB 删除没有给定字段的文件

javascript - Mongoose - 如何在预(保存/更新)中间件中引发多个错误?

node.js - Mongoose - 人口 MissingSchemaError

php - 既然 copydb 已弃用,如何使用 PHP 复制 MongoDB 数据库

node.js - MongoDB auto_reconnect 不起作用