本文介绍了我如何在mongodb中的数组中查找文本搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 {
    "_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模式模式.当我只想搜索蔬菜时,必须输入蔬菜名称.如果我同时搜索蔬菜和水果,则必须同时使用番茄和苹果这两个名称.

Above is my mongo schema modal for my project requirement. When I want to search for vegetables only, vegetable name should have to come. If I search for both vegetables and fruits, both names ie., Tomato and Apple should have to come.

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

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

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

It is giving only documents that have the title Vegetables and not the Vegetables-Home-made. For that I tried to use $elemMatch

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

但是当我们在elemMatch中搜索倍数(即VegetablesFruits)时,它给出了一个错误,我只想在数组中针对特定的标题键(即,

But when we search for multiples ie., Vegetables and Fruits in elemMatch, it is giving an error, I want a text search in a array for particular title key only ie.,

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

推荐答案

这是您想要的:

您可以在$ in运算符中使用正则表达式,如下所示:

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

这篇关于我如何在mongodb中的数组中查找文本搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 04:03