To get an insight into how MongoDB stores data, one concept must be clear, and that is memeory-mapped Files.
memeory-mapped Files
The following figure shows how the database deals with the underlying system.
The memory-mapped file is the OS creates a data file in memory via Mmap, which maps the file to a region of virtual memory.
Virtual memory is an abstraction of physical memory for the process, with an address space of 2^64 size
The operating system maps all the data required by the process to this address space (red line) through Mmap, and then maps the data currently needed to be processed to physical memory (gray lines)
When a process accesses a data, if the data is not in virtual memory, triggers page fault, and then the OS loads the data into virtual and physical memory from the hard disk
If the physical memory is full, triggering the swap-out operation, some data will need to be written back to the disk, if it is pure memory data, write back to the swap partition, if not write back to the disk.
Storage model for MongoDB