You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB结合TypeScript能否实现字段与值的大小写不敏感查询?

在TypeScript中用MongoDB实现大小写不敏感搜索(字段+值)

一、字段键的大小写不敏感搜索

MongoDB默认字段名区分大小写,要匹配不同大小写的字段(比如productionYear和productionyear),可以通过聚合管道的$objectToArray将文档转换为键值对数组,再结合正则匹配字段名:

示例代码(MongoDB官方驱动的TypeScript写法):

import { MongoClient } from 'mongodb';

async function searchByCaseInsensitiveField() {
  const client = await MongoClient.connect('mongodb://localhost:27017');
  const db = client.db('your-db-name');
  const collection = db.collection('your-collection');

  const targetField = 'productionyear';
  const results = await collection.aggregate([
    { $project: { doc: { $objectToArray: '$$ROOT' } } },
    { $unwind: '$doc' },
    { $match: { 'doc.k': { $regex: new RegExp(`^${targetField}$`, 'i') } } },
    { $group: { _id: '$_id', data: { $mergeObjects: { '$arrayToObject': [['$doc']] } } } }
  ]).toArray();

  console.log(results);
  await client.close();
}

这段代码先将文档转成{k: 字段名, v: 值}的数组,匹配不区分大小写的字段名后,再把结果合并回原文档结构。

二、值的大小写不敏感搜索

针对字段值的大小写不敏感匹配,有两种常用方案:

1. 正则表达式($regex + i选项)

直接用$regex指定i修饰符,实现值的大小写不敏感匹配:

// 匹配productionYear字段值包含"2023"(忽略大小写,如2023、2023、2023等)
const results = await collection.find({
  productionYear: { $regex: '2023', $options: 'i' }
}).toArray();

2. Collation(排序规则)

如果需要批量或全局的大小写不敏感查询,可在查询时指定collation参数,设置strength: 2(忽略大小写):

// 匹配productionYear值等于"2023"(忽略大小写)
const results = await collection.find({
  productionYear: '2023'
}, {
  collation: { locale: 'en', strength: 2 }
}).toArray();

这种方式比正则更高效,字段有索引时可利用索引加速查询。

三、同时实现字段和值的大小写不敏感查询

将字段匹配和值匹配逻辑结合,在聚合管道中同时过滤字段名和值:

async function searchFieldAndValueCaseInsensitive() {
  const client = await MongoClient.connect('mongodb://localhost:27017');
  const db = client.db('your-db-name');
  const collection = db.collection('your-collection');

  const targetField = 'productionyear';
  const targetValue = '2023';

  const results = await collection.aggregate([
    { $project: { doc: { $objectToArray: '$$ROOT' } } },
    { $unwind: '$doc' },
    { 
      $match: {
        'doc.k': { $regex: new RegExp(`^${targetField}$`, 'i') },
        'doc.v': { $regex: new RegExp(`^${targetValue}$`, 'i') }
      }
    },
    { $group: { _id: '$_id', data: { $mergeObjects: { '$arrayToObject': [['$doc']] } } } }
  ]).toArray();

  console.log(results);
  await client.close();
}

若追求值匹配的性能,也可结合collation优化,但需注意聚合管道中collation的作用范围。

注意事项

  • 字段名的大小写不敏感查询依赖聚合管道,无法利用字段索引,数据量较大时性能会受影响,建议统一数据库字段命名规范(比如全小写或驼峰),从根源避免这类需求。
  • 值的大小写不敏感查询优先用collation配合索引,比正则表达式性能更优。

内容的提问来源于stack exchange,提问作者N.A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 05:40:16