最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2021年01月11日 11:23:54   作者:Daemon在路上  
這篇文章主要給大家介紹了關于mongoDB使用投影剔除‘額外’字段的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

簡介

實際開發(fā)過程中,為便于開發(fā)人員定位問題,常存在多個額外的字段。例如:增加createdAt、updatedAt字段以查看數(shù)據(jù)的創(chuàng)建和更改時間。而對于客戶端而言,無需知道其存在。針對以上情況,本文詳細介紹了“額外”字段的用途以及處理過程。

技術棧

  • mongodb 4.0.20
  • mongoose 5.10.7

1  "額外"字段是什么

1.1 "額外"是指與業(yè)務無關

mongodb中,collection中存儲的字段并不僅僅有業(yè)務字段。有些情況下,會存儲多余的字段,以便于開發(fā)人員定位問題、擴展集合等。

額外的含義是指 和業(yè)務無關、和開發(fā)相關的字段。這些字段不需要被用戶所了解,但是在開發(fā)過程中是至關重要的。

1.2 產生原因

產生額外字段的原因是多種多樣的。

  • 如使用mongoose插件向db中插入數(shù)據(jù)時,會默認的生成_id、__v字段
  • 如軟刪除,則是通過控制is_deleted實現(xiàn)..

2 額外字段的分類

額外字段的產生原因有很多,可以以此進行分類。

2.1 _id、__v字段

產生原因:以mongoose為例,通過schema->model->entity向mongodb中插入數(shù)據(jù)時,該數(shù)據(jù)會默認的增加_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首次創(chuàng)建時默認生成,表示該條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字段是實現(xiàn)軟刪除一種常用的方式。在實際業(yè)務中,出于各種原因(如刪除后用戶要求再次恢復等),往往采用的軟刪除,而非物理刪除。

因此,is_deleted字段保存當前doc的狀態(tài)。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中。在創(chuàng)建和更新doc時,這兩個字段無需傳入,就會自動變化。

3.2 額外字段清理

通過3.1可以明確的產生若干額外字段,但是客戶端調用接口并返回時,這些字段是無需得知的。因此需對額外字段進行清理。清理方式分為投影和過濾。

以query、update接口為例。其中query接口用于:1、查詢指定字段 2、查詢全部字段 3、分頁排序查詢。update接口用于更新并返回更新后的數(shù)據(jù)。

根據(jù)是否需要指定字段、和collection中有無內嵌的情況劃分,一共有4類。接著針對這4種情況進行分析。

1、有指定字段、無內嵌

2、無指定字段、無內嵌

3、有指定字段、有內嵌

4、無指定字段、有內嵌

3.2.1 投影

有指定字段是指在查詢時指定查詢字段,而無需全部返回。mongo中實現(xiàn)指定的方式是投影 (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處理),是數(shù)據(jù)庫中真實狀態(tài)。因此需要對產生的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;
}

細心的讀者已經發(fā)現(xiàn)了,投影和過濾的字段內容都是額外字段。那什么情況下使用投影,什么情況下使用過濾呢?

關于這個問題,筆者的建議是如果不能確保額外字段被剔除掉,那就采取雙重認證:查詢前使用投影,查詢后使用過濾。

4 總結

本文介紹了實際業(yè)務中往往會產生額外字段。而在mongoDB中,"消除"額外字段的手段主要是投影、過濾。

以使用頻率最高的查詢接口為例,整理如下:

指定選項 內嵌選項 查詢前投影 查詢后過濾
有指定 無內嵌 ×
有指定 有內嵌 ×
無指定 無內嵌 ×
無指定 有內嵌 ×

因此,筆者建議無論schema中是否配置了options,在查詢時組裝投影語句,查詢后進行結果過濾。這樣保證萬無一失,

額外字段才不會漏到客戶端**。

到此這篇關于mongoDB使用投影剔除‘額外'字段的文章就介紹到這了,更多相關mongoDB用投影剔除額外字段內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • MongoDB卸載安裝的詳細安裝教程

    MongoDB卸載安裝的詳細安裝教程

    MongoDB是一個是一個基于分布式文件存儲的數(shù)據(jù)庫,下面這篇文章主要給大家介紹了關于MongoDB卸載安裝的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-04-04
  • mongodb 集群重構和釋放磁盤空間實例詳解

    mongodb 集群重構和釋放磁盤空間實例詳解

    這篇文章主要介紹了mongodb 集群重構和釋放磁盤空間實例詳解的相關資料,具有一定的參考價值,需要的朋友可以參考下
    2016-11-11
  • 淺析mongodb中group分組

    淺析mongodb中group分組

    這篇文章主要介紹了淺析mongodb中group分組的實現(xiàn)方法及示例,非常的簡單實用,有需要的小伙伴可以參考下。
    2015-05-05
  • MongoDB數(shù)據(jù)庫基礎操作總結

    MongoDB數(shù)據(jù)庫基礎操作總結

    這篇文章主要介紹了MongoDB數(shù)據(jù)庫基礎操作,結合實例形式總結分析了MongoDB數(shù)據(jù)庫創(chuàng)建、刪除、集合、文檔等基本操作技巧,需要的朋友可以參考下
    2020-06-06
  • MongoDB學習以及集群搭建的實踐全紀錄

    MongoDB學習以及集群搭建的實踐全紀錄

    這篇文章主要給大家介紹了關于MongoDB學習以及集群搭建的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-09-09
  • mongoDB使用投影剔除‘額外’字段的操作過程

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

    這篇文章主要給大家介紹了關于mongoDB使用投影剔除‘額外’字段的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01
  • Mongo復制集同步驗證的實例詳解

    Mongo復制集同步驗證的實例詳解

    這篇文章主要介紹了mongo復制集同步驗證的實例詳解的相關資料,這里提供實現(xiàn)的方法及示例代碼,幫助大家學習理解,需要的朋友可以參考下
    2017-07-07
  • MongoDB數(shù)據(jù)庫查看慢查詢級別以及慢查詢日志

    MongoDB數(shù)據(jù)庫查看慢查詢級別以及慢查詢日志

    最近項目上一直在用mongodb作為數(shù)據(jù)庫,mongodb有他的優(yōu)勢,文檔型類json格式存儲數(shù)據(jù),修改起來更方便,但是最近在用mongodb出現(xiàn)了查詢緩慢的問題,這篇文章主要給大家介紹了關于MongoDB數(shù)據(jù)庫查看慢查詢級別以及慢查詢日志的相關資料,需要的朋友可以參考下
    2023-05-05
  • NoSQL優(yōu)缺點與MongoDB數(shù)據(jù)庫簡介

    NoSQL優(yōu)缺點與MongoDB數(shù)據(jù)庫簡介

    這篇文章介紹了NoSQL的優(yōu)缺點與MongoDB數(shù)據(jù)庫,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-06-06
  • Mongodb實戰(zhàn)之全文搜索功能

    Mongodb實戰(zhàn)之全文搜索功能

    全文檢索對每一個詞建立一個索引,指明該詞在文章中出現(xiàn)的次數(shù)和位置,當用戶查詢時,檢索程序就根據(jù)事先建立的索引進行查找,并將查找的結果反饋給用戶的檢索方式。下面這篇文章主要給大家介紹了Mongodb全文搜索功能的相關資料,需要的朋友可以參考下。
    2017-07-07

最新評論

蛟河市| 扶沟县| 阿拉善左旗| 漾濞| 东兴市| 邛崃市| 定安县| 云安县| 谢通门县| 上虞市| 肇源县| 宿州市| 遵义市| 寿宁县| 方正县| 福建省| 达尔| 韩城市| 襄樊市| 江门市| 二连浩特市| 抚顺市| 紫金县| 大冶市| 柏乡县| 常宁市| 柘荣县| 永善县| 集安市| 江达县| 呼和浩特市| 保定市| 大余县| 拉孜县| 陈巴尔虎旗| 江北区| 宁安市| 安乡县| 日土县| 巍山| 万盛区|