服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - MongoDB - mongoDB使用投影剔除‘额外’字段的操作过程

mongoDB使用投影剔除‘额外’字段的操作过程

2021-02-22 17:07Daemon在路上 MongoDB

这篇文章主要给大家介绍了关于mongoDB使用投影剔除‘额外’字段的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

 

简介

 

实际开发过程中,为便于开发人员定位问题,常存在多个额外字段。例如:增加createdAt、updatedAt字段以查看数据的创建和更改时间。而对于客户端而言,无需知道其存在。针对以上情况,本文详细介绍了“额外”字段的用途以及处理过程。

技术栈

  • 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代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
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投影语句组装代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 添加通用筛选条件
* @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过滤和内嵌文档过滤。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * 处理自身及内嵌的表
 * @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使用投影剔除‘额外'字段的文章就介绍到这了,更多相关mongoDB用投影剔除额外字段内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.cn/post/6915767241640247309

延伸 · 阅读

精彩推荐
  • MongoDBMongoDB分片测试

    MongoDB分片测试

    分片是mongoDB扩展的一种方式。分片分割一个collection并将不同的部分存储在不同的机器上,本文给大家介绍MongoDB分片测试,需要的朋友参考下吧 ...

    我思,故我在5532020-05-05
  • MongoDBMongo服务重启异常问题的处理方法

    Mongo服务重启异常问题的处理方法

    这篇文章主要给大家介绍了关于Mongo服务重启异常问题的处理方法,这个问题其实还是挺常见的,通过此文学习处理方法,以后遇到了就不会措手不及的,需要的...

    Leafage11842021-08-24
  • MongoDB将MongoDB加入到Windows的本地服务项的方法

    将MongoDB加入到Windows的本地服务项的方法

    下面主要针对MongoDB在Windows下加入本地服务项做一些简单的分享。以方便刚接触MongoDB并在Windows环境下进行开发的同学 ...

    MongoDB教程网3012020-04-28
  • MongoDBMongodb如何开启用户访问控制详解

    Mongodb如何开启用户访问控制详解

    默认启动 MongoDB 服务时没有任何参数,可以对数据库任意操 作,而且可以远程访问数据库,所以推荐开发阶段可以不设置任何参数,但对于生产环境还是要...

    不争5402020-05-10
  • MongoDBMongoDB 简单入门教程(安装、基本概念、创建用户)

    MongoDB 简单入门教程(安装、基本概念、创建用户)

    这篇文章主要介绍了MongoDB 简单入门教程(安装、基本概念、创建用户)的相关资料,帮助大家更好的理解和学习使用MongoDB数据库,感兴趣的朋友可以了解下...

    AsiaYe6352021-05-10
  • MongoDBMongoDB 学习笔记

    MongoDB 学习笔记

    最近在学习MongoDB,小结一下,主要都是一些基础知识,需要的朋友可以参考下 ...

    服务器之家3412020-04-25
  • MongoDBMongodb数据库误删后的恢复方法(两种)

    Mongodb数据库误删后的恢复方法(两种)

    本文给大家分享两种方法来实现Mongodb数据库误删后的恢复,每种方法给大家介绍的都非常详细,需要的朋友参考下吧 ...

    fyg05249922020-05-18
  • MongoDBMongoDB简单操作示例【连接、增删改查等】

    MongoDB简单操作示例【连接、增删改查等】

    这篇文章主要介绍了MongoDB简单操作,涉及命令行窗口下使用MongoDB进行简单的连接、增删改查等相关操作技巧,需要的朋友可以参考下 ...

    tinyphp2982020-05-23