How do I make case-insensitive queries on Mongodb?

后端 未结 12 1171
北恋
北恋 2020-11-27 12:02
var thename = \'Andrew\';
db.collection.find({\'name\':thename});

How do I query case insensitive? I want to find result even if \"andrew\";

12条回答
  •  清酒与你
    2020-11-27 12:18

    ... with mongoose on NodeJS that query:

    const countryName = req.params.country;
    
    { 'country': new RegExp(`^${countryName}$`, 'i') };
    

    or

    const countryName = req.params.country;
    
    { 'country': { $regex: new RegExp(`^${countryName}$`), $options: 'i' } };
    
    // ^australia$
    

    or

    const countryName = req.params.country;
    
    { 'country': { $regex: new RegExp(`^${countryName}$`, 'i') } };
    
    // ^turkey$
    

    A full code example in Javascript, NodeJS with Mongoose ORM on MongoDB

    // get all customers that given country name
    app.get('/customers/country/:countryName', (req, res) => {
        //res.send(`Got a GET request at /customer/country/${req.params.countryName}`);
    
        const countryName = req.params.countryName;
    
        // using Regular Expression (case intensitive and equal): ^australia$
    
        // const query = { 'country': new RegExp(`^${countryName}$`, 'i') };
        // const query = { 'country': { $regex: new RegExp(`^${countryName}$`, 'i') } };
        const query = { 'country': { $regex: new RegExp(`^${countryName}$`), $options: 'i' } };
    
        Customer.find(query).sort({ name: 'asc' })
            .then(customers => {
                res.json(customers);
            })
            .catch(error => {
                // error..
                res.send(error.message);
            });
    });
    

提交回复
热议问题