Mongodb에서 대소문자를 구분하지 않는 쿼리를 작성하려면 어떻게 해야 합니까?
var thename = 'Andrew';
db.collection.find({'name':thename});
대소문자를 구분하지 않는 쿼리 방법은?'andrew'라도 결과를 찾고 싶다.
Chris Fulstow의 솔루션은 (+1) 동작합니다만, 특히 컬렉션이 매우 많은 경우에는 효율적이지 않을 수 있습니다.가 없는 표현로 하지 않는 )^
정규 또, 를 하고 있는 것( 「 」 ) i
대소문자를 구분하지 않는 플래그는 인덱스가 존재하더라도 인덱스를 사용하지 않습니다.
하는 것도 할 수 .name
: ((:name_lower
그런 다음 다음과 같이 대소문자를 구분하지 않는 정확한 일치를 효율적으로 쿼리할 수 있습니다(특히 인덱스가 있는 경우).
db.collection.find({"name_lower": thename.toLowerCase()})
또는 다음과 같은 프리픽스 일치(루트 정규 표현)를 사용합니다.
db.collection.find( {"name_lower":
{ $regex: new RegExp("^" + thename.toLowerCase(), "i") } }
);
두 쿼리 지수를 합니다.name_lower
.
이 경우 대소문자를 구분하지 않는 정규 표현을 사용해야 합니다.
db.collection.find( { "name" : { $regex : /Andrew/i } } );
의 thename
변수를 지정하여 새 RegExp 개체를 만듭니다.
var thename = "Andrew";
db.collection.find( { "name" : { $regex : new RegExp(thename, "i") } } );
업데이트: 정확하게 일치하려면 regex를 사용해야 합니다."name": /^Andrew$/i
야닉엘 덕분이에요
이렇게 해결했어요.
var thename = 'Andrew';
db.collection.find({'name': {'$regex': thename,$options:'i'}});
대소문자를 구분하지 않고 정확하게 조회하려면 다음과 같이 하십시오.
var thename = '^Andrew$';
db.collection.find({'name': {'$regex': thename,$options:'i'}});
Mongoose(및 노드)에서는 다음과 같이 동작했습니다.
User.find({ email: /^name@company.com$/i })
User.find({ email: new RegExp(
"emailVariable}$" ('i') }"
MongoDB에서는 다음과 같이 동작했습니다.
db.users.find({ email: { $regex: /^name@company.com$/i }})
두 줄 모두 대소문자를 구분하지 않습니다. 수 .NaMe@CompanY.Com
줄 를 찾을 수 .
'아주 좋다', '아주 좋다', '아주 좋다'도 쓸 수 요./^NaMe@CompanY.Com$/i
수 .name@company.com
DB db db db 、 [ DB 。
MongoDB 3.4에는 대소문자를 구분하지 않는 진정한 인덱스를 만들 수 있는 기능이 포함되어 있어 대규모 데이터셋에서 대소문자를 구분하지 않는 검색 속도가 대폭 향상됩니다.강도 2의 대조값을 지정하여 만듭니다.
가장 쉬운 방법은 데이터베이스에 대조 설정을 하는 것입니다.그러면 모든 쿼리가 해당 조회를 상속하고 이를 사용합니다.
db.createCollection("cities", { collation: { locale: 'en_US', strength: 2 } } )
db.names.createIndex( { city: 1 } ) // inherits the default collation
다음과 같이 할 수도 있습니다.
db.myCollection.createIndex({city: 1}, {collation: {locale: "en", strength: 2}});
그리고 이렇게 사용하세요.
db.myCollection.find({city: "new york"}).collation({locale: "en", strength: 2});
이렇게 하면 "뉴욕", "뉴욕", "뉴욕" 등으로 명명된 도시가 반환됩니다.
상세한 것에 대하여는, https://jira.mongodb.org/browse/SERVER-90 를 참조해 주세요.
노드에 mongoose가 있는 경우쿼리하는 JS:
const countryName = req.params.country;
{ 'country': new RegExp(`^${countryName}$`, 'i') };
또는
const countryName = req.params.country;
{ 'country': { $regex: new RegExp(`^${countryName}$`), $options: 'i' } };
// ^australia$
또는
const countryName = req.params.country;
{ 'country': { $regex: new RegExp(`^${countryName}$`, 'i') } };
// ^turkey$
Javascript, MongoDB에서 Mongoose ORM을 사용하는 NodeJS의 완전한 코드 예시
// 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);
});
});
대/소문자를 구분하지 않는 문자열을 찾으려면 다음 명령을 사용합니다.
var thename = "Andrew";
db.collection.find({"name":/^thename$/i})
몇 시간 전에 이 문제를 풀었어요.
var thename = 'Andrew'
db.collection.find({ $text: { $search: thename } });
- 이 방법으로 쿼리를 수행할 경우 대소문자 구분 및 분음 부호 구분은 기본적으로 false로 설정됩니다.
Andrew 사용자 오브젝트에서 필요한 필드를 선택하여 다음과 같이 확장할 수도 있습니다.
db.collection.find({ $text: { $search: thename } }).select('age height weight');
참고 자료: https://docs.mongodb.org/manual/reference/operator/query/text/ #text
대소문자를 구분하지 않는 인덱스를 사용할 수 있습니다.
다음 예제에서는 기본 조회가 없는 컬렉션을 작성한 후 대소문자를 구분하지 않는 조회를 사용하여 이름 필드에 인덱스를 추가하는 방법을 보여 줍니다.Unicode의 국제 컴포넌트
/*
* strength: CollationStrength.Secondary
* Secondary level of comparison. Collation performs comparisons up to secondary * differences, such as diacritics. That is, collation performs comparisons of
* base characters (primary differences) and diacritics (secondary differences). * Differences between base characters takes precedence over secondary
* differences.
*/
db.users.createIndex( { name: 1 }, collation: { locale: 'tr', strength: 2 } } )
인덱스를 사용하려면 쿼리에서 동일한 데이터 정렬을 지정해야 합니다.
db.users.insert( [ { name: "Oğuz" },
{ name: "oğuz" },
{ name: "OĞUZ" } ] )
// does not use index, finds one result
db.users.find( { name: "oğuz" } )
// uses the index, finds three results
db.users.find( { name: "oğuz" } ).collation( { locale: 'tr', strength: 2 } )
// does not use the index, finds three results (different strength)
db.users.find( { name: "oğuz" } ).collation( { locale: 'tr', strength: 1 } )
또는 디폴트 대조로 컬렉션을 작성할 수 있습니다.
db.createCollection("users", { collation: { locale: 'tr', strength: 2 } } )
db.users.createIndex( { name : 1 } ) // inherits the default collation
이것은 완벽하게 작동될 것이다.
db.collection.find({ song_Name: { '$regex': searchParam, $options: 'i' } })
regex를 추가하기만 하면 됩니다.$options: 'i'
대소문자를 구분하지 않습니다.
대소문자를 구분하지 않는 리터럴 문자열을 찾으려면:
regex 사용(권장)
db.collection.find({
name: {
$regex: new RegExp('^' + name.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$', 'i')
}
});
소문자 색인 사용(빠른 속도)
db.collection.find({
name_lower: name.toLowerCase()
});
정규 표현은 리터럴 문자열 매칭보다 느립니다.단, 소문자 필드가 추가되면 코드가 복잡해집니다.복잡도가 높아집니다.의심이 들 때는 정규 표현을 사용하세요.필드를 대체할 수 있는 경우, 즉 처음부터 대소문자를 사용하지 않는 경우에만 명시적으로 소문자를 사용하는 것이 좋습니다.
regex 전에 이름을 이스케이프해야 합니다.사용자 입력 와일드카드를 사용하는 경우,.replace(/%/g, '.*')
'a%'를 일치시켜 'a'로 시작하는 모든 이름을 찾을 수 있습니다.
정규식 쿼리는 인덱스 기반 쿼리보다 느립니다.
다음과 같이 특정 조합으로 인덱스를 생성할 수 있습니다.
db.collection.createIndex({field:1},{collation: {locale:'en',strength:2}},{background : true});
위의 쿼리는 문자열의 대소문자를 무시하는 인덱스를 만듭니다.대조는 대소문자를 구분하지 않는 인덱스를 사용하기 위해 각 쿼리에서 지정해야 합니다.
쿼리
db.collection.find({field:'value'}).collation({locale:'en',strength:2});
참고 - 각 쿼리와의 조회를 지정하지 않으면 쿼리에서 새 인덱스를 사용하지 않습니다.
자세한 내용은 이쪽의 mongodb 문서를 참조해 주세요.https://docs.mongodb.com/manual/core/index-case-insensitive/
다음 쿼리는 필요한 문자열이 무감각하고 전역 오카렌스인 문서를 찾습니다.
db.collection.find({name:{
$regex: new RegExp(thename, "ig")
}
},function(err, doc) {
//Your code here...
});
아래와 같이 $toLower를 사용하는 것이 쉬운 방법입니다.
db.users.aggregate([
{
$project: {
name: { $toLower: "$name" }
}
},
{
$match: {
name: the_name_to_search
}
}
])
언급URL : https://stackoverflow.com/questions/7101703/how-do-i-make-case-insensitive-queries-on-mongodb
'sourcecode' 카테고리의 다른 글
Switch'가 'react-router-dom'에서 내보내지지 않았습니다. (0) | 2023.03.04 |
---|---|
Node.js에서 약속과 함께 MongoDB를 사용하는 방법 (0) | 2023.03.04 |
com.sysml.syscl.syscind.exc를 지정합니다.인식할 수 없는 속성 예외:인식할 수 없는 필드 (0) | 2023.03.04 |
기본 MongoDB 쉘로 예쁘게 인쇄 (0) | 2023.03.04 |
무엇을 선택해야 합니까?MongoDB/Cassandra/Redis/CouchDB? (0) | 2023.02.27 |