简体   繁体   中英

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.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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