简体   繁体   English

MONGODB:根据一次查询查找所有出现的名字或姓氏

[英]MONGODB: find all occurencies of first or lastname according to one query

I want to find all occurencies on my DB according to firstname and lastname (the user is invited to enter what ever he wants in the search bar), and I'm supposed to return all persons who has firstname or lastname which matches that query.我想根据名字和姓氏查找我的数据库中的所有事件(邀请用户在搜索栏中输入他想要的任何内容),并且我应该返回所有名字或姓氏与该查询匹配的人。

I already have a solution, but I feel that there will be a better one.我已经有了解决方案,但我觉得会有更好的解决方案。 Here's mine:这是我的:

maladeModel.find ({},{nom: 1, prenom: 1, dateNaissance :1, adresse :1, photoIdentite :1},(err, malades) => {
        if (err) {
            res.status(500).json ({
                type: "Err" ,
                message : "Server not responding"
            });
        }
        return malades;
    }).then (malades=> 
       {
            malades = malades.filter(malade=> {
               return malade.nom.toUpperCase().includes(req.body.key.toUpperCase())
               ||
                malade.prenom.toUpperCase().includes(req.body.key.toUpperCase())
            });
           res.status(200).json ({type :"Info",  message: "Le malade est trouve" , malades});
        }
    );

use this one mongodb aggregate inbuild filter is always optimal to use.使用这个 mongodb 聚合内置过滤器始终是最佳使用。

 maladeModel.aggregate([
    {
           $project:{
               nom: { $toLower: "$nom" },
               prenom: { $toLower: "$prenom" },
               dateNaissance :1, adresse :1, photoIdentite :1
             }

    },
     {
       $match:{
             $or:[
                   {nom: req.body.key.toLowerCase()},
                   {prenom: req.body.key.toLowerCase()}
                 ]
             }
    }

    ]).exec(function(err, malades) {
    res.status(200).json ({type :"Info",  message: "Le malade est trouve" , malades});
    });

for simplicity you can just do为简单起见,您可以这样做

    maladeModel.find({
      $or:[
      {nom: req.body.key.toLowerCase()},
      {prenom: req.body.key.toLowerCase()}
     ]
     }, {dateNaissance :1, adresse :1, photoIdentite :1}).then(malades =>{
     res.status(200).json({type :"Info",  message: "Le malade est trouve" , malades});
    }).catch(err => res.status(500).json({message: err.message})) 

this will get you all the matching documents in your database but I think indexing is the fastest.这将为您提供数据库中的所有匹配文档,但我认为索引是最快的。 You can check it你可以检查一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM