Case Insensitive search with $in

后端 未结 6 1412
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 05:46

How to search a column in a collection in mongodb with $in which includes an array of elements for search and also caseInsensitive matching of thos

6条回答
  •  死守一世寂寞
    2020-12-15 06:33

    Use $in with the match being case insensitive:

    Data example:

    { 
        name : "...Event A",
        fieldX : "aAa" 
    },
    { 
      name : "...Event B",
      fieldX : "Bab" 
    },
    { 
      name : "...Event C",
      fieldX : "ccC" 
    },
    { 
      name : "...Event D",
      fieldX : "dDd" 
    }
    

    And we want documents were "fieldX" is contained in any value of the array (optValues):

    var optValues = ['aaa', 'bbb', 'ccc', 'ffffd'];
    
    var optRegexp = [];
    optValues.forEach(function(opt){
            optRegexp.push(  new RegExp(opt, "i") );
    });
    
    db.collection.find( { fieldX: { $in: optRegexp } } );
    

    This works for $all either.

    I hope this helps!

    p.s.: This was my solution to search by tags in a web application.

提交回复
热议问题