怎么在mongoDB中利用投影剔除字段
创始人
2024-12-28 10:01:07
0次

技术栈

  • mongodb 4.0.20

  • mongoose 5.10.7

1  "额外"字段是什么

1.1 "额外"是指与业务无关

mongodb中,collection中存储的字段并不仅仅有业务字段。有些情况下,会存储多余的字段,以便于开发人员定位问题、扩展集合等。

额外的含义是指 和业务无关、和开发相关的字段。这些字段不需要被用户所了解,但是在开发过程中是至关重要的。

1.2 产生原因

产生额外字段的原因是多种多样的。

  • 如使用mongoose插件向db中插入数据时,会默认的生成_id、__v字段

  • 如软删除,则是通过控制is_deleted实现..

2 额外字段的分类

额外字段的产生原因有很多,可以以此进行分类。

2.1 _id、__v字段

产生原因:以mongoose为例,通过schema->model->entity向mongodb中插入数据时,该数据会默认的增加_id、__v字段。

_id字段是由mongodb默认生成的,用于文档的唯一索引。类型是ObjectID。mongoDB文档定义如下:

“
MongoDB creates a unique index on the _id field during the creation of a collection. The _id index prevents clients from inserting two documents with the same value for the _id field. You cannot drop this index on the _id field.<

__v字段是由mongoose首次创建时默认生成,表示该条doc的内部版本号。

“
The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The versionKey option is a string that represents the path to use for versioning. The default is __v.

2.2 createdAt、updatedAt字段

createdAt、updatedAt字段是通过timestamp选项指定的,类型为Date。

“
The timestamps option tells mongoose to assign createdAt and updatedAt fields to your schema. The type assigned is Date.By default, the names of the fields are createdAt and updatedAt. Customize the field names by setting timestamps.createdAt and timestamps.updatedAt.

2.3 is_deleted字段

is_deleted字段是实现软删除一种常用的方式。在实际业务中,出于各种原因(如删除后用户要求再次恢复等),往往采用的软删除,而非物理删除。

因此,is_deleted字段保存当前doc的状态。is_deleted字段为true时,表示当前记录有效。is_deleted字段为false时,表示当前记录已被删除。

3 额外字段相关操作

3.1 额外字段生成

_id字段是必选项;__v、createdAt、updatedAt字段是可配置的;status字段直接加在s对应的chema中。相关的schema代码如下:

isdeleted: {
 type: String,
 default:true,
 enum: [true, false],
},
id: {
 type: String,
 index: true,
 unqiue: true,
 default:uuid.v4(),
}},
{timestamps:{createdAt:'docCreatedAt',updatedAt:"docUpdatedAt"},versionKey:false});

通过配置schema中的timestamps选项,可以将createdAt和updatedAt字段加入到doc中。在创建和更新doc时,这两个字段无需传入,就会自动变化。

3.2 额外字段清理

通过3.1可以明确的产生若干额外字段,但是客户端调用接口并返回时,这些字段是无需得知的。因此需对额外字段进行清理。清理方式分为投影和过滤。

以query、update接口为例。其中query接口用于:1、查询指定字段 2、查询全部字段 3、分页排序查询。update接口用于更新并返回更新后的数据。

根据是否需要指定字段、和collection中有无内嵌的情况划分,一共有4类。接着针对这4种情况进行分析。

1、有指定字段、无内嵌

2、无指定字段、无内嵌

3、有指定字段、有内嵌

4、无指定字段、有内嵌

3.2.1 投影

有指定字段是指在查询时指定查询字段,而无需全部返回。mongo中实现指定的方式是投影 (project) 。mongo官方文档中定义如下:

“
The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields.

$project可以做3件事:

1.指定包含的字段、禁止_id字段、添加新字段

2.重置已存在字段的值

3.指定排除的字段

我们只需关注事情1、事情3。接着查看mongoose中对project的说明:

“
When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the schema level.

A projection must be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default.

注意:此处指query "projection"

mongoose表明:投影要么是全包含,要么是全剔除。不允许包含和剔除同时存在。但由于

_id是MongoDB默认包含的,因此_id是个例外。

select project投影语句组装代码:

 /**
 * 添加通用筛选条件
 * @param {*} stat 已装配的筛选语句 
 * @param {*} collection collectionName
 * @return {*} 组装完成的语句
 */
 function addCommonSelectCond(stat,collection)
 {
 if(typeof(stat)!="object") return;

 stat["_id"] = 0;
 stat["__v"] = 0;
 stat["status"] = 0;
 stat["docCreatedAt"] = 0;
 stat["docUpdatedAt"] = 0;

 var embeddedRes = hasEmbedded(collection);
 if(embeddedRes["isEmbedded"])
 {
 for(var item of embeddedRes["embeddedSchema"])
 {
 stat[item+"._id"] = 0;
 stat[item+".__v"] = 0;
 stat[item+".status"] = 0;
 stat[item+".docCreatedAt"] = 0; 
 stat[item+".docUpdatedAt"] = 0; 
 }
 }
 return stat;
 }
3.2.2 过滤

通过findOneAndupdate、insert、query等返回的doc对象中(已经过lean或者toObject处理),是数据库中真实状态。因此需要对产生的doc进行过滤,包括doc过滤和内嵌文档过滤。

/**
 * 处理自身及内嵌的表
 * @param {*} collection 查询的表
 * @param {*} doc 已查询出的结果
 * @returns doc 清理后的结果
 */
static clearDoc(collection,doc){
 if(doc === undefined || doc === null || typeof doc != "object" ) return null;
 doc = this.clearExtraField(doc);

 var res = hasEmbedded(collection);
 if(res["isEmbedded"])
 {
 let arr = res["embeddedSchema"];
 for(var item of arr){
 if(doc[item])
 doc[item] = this.clearArray(doc[item]);
 }
 }
 return doc;
}

static clearExtraField(doc){
 if(doc === null || typeof doc != "object")
 return;
 
 var del = delete doc["docCreatedAt"]&&
 delete doc["docUpdatedAt"]&&
 delete doc["_id"]&&
 delete doc["__v"]&&
 delete doc["status"];
 if(!del) return new Error("删除额外字段出错");

 return doc;
}

static clearArray(arr)
{
 if(!Array.isArray(arr)) return;

 var clearRes = new Array();
 for(var item of arr){
 clearRes.push(this.clearExtraField(item));
 }
 return clearRes;
}

细心的读者已经发现了,投影和过滤的字段内容都是额外字段。那什么情况下使用投影,什么情况下使用过滤呢?

关于这个问题,笔者的建议是如果不能确保额外字段被剔除掉,那就采取双重认证:查询前使用投影,查询后使用过滤。

4 总结

本文介绍了实际业务中往往会产生额外字段。而在mongoDB中,"消除"额外字段的手段主要是投影、过滤。

以使用频率最高的查询接口为例,整理如下:

指定选项内嵌选项查询前投影查询后过滤
有指定无内嵌×√
有指定有内嵌×√
无指定无内嵌√×
无指定有内嵌√×

因此,笔者建议无论schema中是否配置了options,在查询时组装投影语句,查询后进行结果过滤。这样保证万无一失,

额外字段才不会漏到客户端**。

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...