---
title: "8: Preallocate space, whenever possible"
author: "dikar"
date: "2011-05-04T22:56:27Z"
tags: ["MongoDB"]
categories: ["编程语言"]
slug: "8-preallocate-space-whenever-possible"
draft: false
lastmod: "2011-05-04T22:56:27Z"
id: 1028870
url: "https://dikar.iteye.com/blog/1028870"
---

原文如下：

 

This is closely related to both “Tip #6: Do not embed fields that have unbound

growth” on page 7 and “Tip #7: Pre-populate anything you can” on page 8. This is an

optimization for once you know that your documents usually grow to a certain size,

but they start out at a smaller size. When you initially insert the document, add a

garbage field that contains a string the size that the document will (eventually) be, then

immediately unset that field:

    &gt; collection.insert({"\_id" : 123, /* other fields \*/, "garbage" : someLongString})

    &gt; collection.update({"\_id" : 123}, {"$unset" : {"garbage" : 1}})

This way, MongoDB will initially place the document somewhere that gives it enough

room to grow (Figure 1-3).

看下unset的定义

[http://www.mongodb.org/display/DOCS/Updating#Updating-%24unset](http://www.mongodb.org/display/DOCS/Updating#Updating-%24unset)

类似占位符之类的，可能mongoDB对于unset后的字段空间不会删除，只是做一下标记，这样这部分空间已经预先分出来了，这个空间就可以被重用