温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在mongoDB中利用投影剔除字段

发布时间:2021-01-11 14:47:10 来源:亿速云 阅读:258 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关怎么在mongoDB中利用投影剔除字段,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

技术栈

  • 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,在查询时组装投影语句,查询后进行结果过滤。这样保证万无一失,

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

看完上述内容,你们对怎么在mongoDB中利用投影剔除字段有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI