MongoDB: Is it possible to make a case-insensitive query?

后端 未结 24 2248
谎友^
谎友^ 2020-11-22 04:44

Example:

> db.stuff.save({\"foo\":\"bar\"});

> db.stuff.find({\"foo\":\"bar\"}).count();
1
> db.stuff.find({\"foo\":\"BAR\"}).count();
0

24条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 05:21

    TL;DR

    Correct way to do this in mongo

    Do not Use RegExp

    Go natural And use mongodb's inbuilt indexing , search

    Step 1 :

    db.articles.insert(
       [
         { _id: 1, subject: "coffee", author: "xyz", views: 50 },
         { _id: 2, subject: "Coffee Shopping", author: "efg", views: 5 },
         { _id: 3, subject: "Baking a cake", author: "abc", views: 90  },
         { _id: 4, subject: "baking", author: "xyz", views: 100 },
         { _id: 5, subject: "Café Con Leche", author: "abc", views: 200 },
         { _id: 6, subject: "Сырники", author: "jkl", views: 80 },
         { _id: 7, subject: "coffee and cream", author: "efg", views: 10 },
         { _id: 8, subject: "Cafe con Leche", author: "xyz", views: 10 }
       ]
    )
     
    

    Step 2 :

    Need to create index on whichever TEXT field you want to search , without indexing query will be extremely slow

    db.articles.createIndex( { subject: "text" } )
    

    step 3 :

    db.articles.find( { $text: { $search: "coffee",$caseSensitive :true } } )  //FOR SENSITIVITY
    db.articles.find( { $text: { $search: "coffee",$caseSensitive :false } } ) //FOR INSENSITIVITY
    
    
     
    

提交回复
热议问题