FAQ: MongoDB Fundamentals

This document answers some common questions about MongoDB.

What platforms does MongoDB support?

For the list of supported platforms, seeSupported Platforms.

Is MongoDB offered as a hosted service?

Yes. MongoDB Atlas isa cloud-hosted database-as-a-service. For more information, pleasevisit the MongoDB Atlas docs.

How does a collection differ from a table?

Instead of tables, a MongoDB database stores its data incollections. A collection holds one or moreBSON documents. Documents are analogousto records or rows in a relational database table. Each document hasone or more fields; fields are similar tothe columns in a relational database table.

See also

SQL to MongoDB Mapping Chart, Introduction to MongoDB

How do I create a database and a collection?

If a database does not exist, MongoDB creates the database when youfirst store data for that database.

If a collection does not exist, MongoDB creates the collection when youfirst store data for that collection. [1]

As such, you can switch to a non-existent database (use <dbname>)and perform the following operation:

  1. use myNewDB
  2.  
  3. db.myNewCollection1.insertOne( { x: 1 } )
  4. db.myNewCollection2.createIndex( { a: 1 } )

The insert operation creates both the database myNewDB and thecollection myNewCollection1 if they do not already exist.

The createIndex operation, which occurs after the myNewDB hasbeen created, creates the index and the collection myNewCollection2if the collection does not exist. If myNewDb did not exist, thecreateIndex operation would have also created the myNewDB.

[1]You can also create a collection explicitly usingdb.createCollection if you want to specify specificoptions, such as maximum size or document validation rules.

How do I define or alter the collection schema?

You do not need to specify a schema for a collection in MongoDB.Although it is common for the documents in a collection to have alargely homogeneous structure, it is not a requirement; i.e. documentsin a single collection do not need to have the same set of fields. Thedata type for a field can differ across documents in a collection aswell.

To change the structure of the documents in a collection, update thedocuments to the new structure. For instance, add new fields, removeexisting ones, or update the value of a field to a new type.

Changed in version 3.2: Starting in MongoDB 3.2, however, you can enforce documentvalidation rules for a collectionduring update and insert operations.

Some collection properties, such as specifying a maximum size, can bespecified during the explicit creation of a collection and be modified.See db.createCollection and collMod. If you arenot specifying these properties, you do not need to explicitly createthe collection since MongoDB creates new collections when you firststore data for the collections.

Does MongoDB support SQL?

Not directly, no. However, MongoDB does support a rich query language of its own. Forexamples on using MongoDB’s query language, seeMongoDB CRUD Operations

You can also use the MongoDB Connector for BI to queryMongoDB collections with SQL.

See also

SQL to MongoDB Mapping Chart

Does MongoDB support transactions?

Because a single document can contain related data that would otherwisebe modeled across separate parent-child tables in a relational schema,MongoDB’s atomic single-document operations already provide transactionsemantics that meet the data integrity needs of the majority ofapplications. One or more fields may be written in a single operation,including updates to multiple sub-documents and elements of an array.The guarantees provided by MongoDB ensure complete isolation as adocument is updated; any errors cause the operation to roll back sothat clients receive a consistent view of the document.

However, for situations that require atomicity of reads and writesto multiple documents (in a single or multiple collections), MongoDBsupports multi-document transactions:

  • In version 4.0, MongoDB supports multi-document transactions onreplica sets.

  • In version 4.2, MongoDB introduces distributed transactions,which adds support for multi-document transactions on shardedclusters and incorporates the existing support formulti-document transactions on replica sets.

For details regarding transactions in MongoDB, see theTransactions page.

Important

In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.

For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.

Does MongoDB handle caching?

Yes. MongoDB keeps most recently used data in RAM. If you have createdindexes for your queries and your working data set fits in RAM, MongoDBserves all queries from memory.

MongoDB does not cache the query results in order to return the cachedresults for identical queries.

For more information on MongoDB and memory use, see WiredTigerand Memory Use.

How does MongoDB address SQL or Query injection?

BSON

As a client program assembles a query in MongoDB, it builds a BSONobject, not a string. Thus traditional SQL injection attacks are not aproblem. More details and some nuances are covered below.

MongoDB represents queries as BSON objects. Typicallyclient libraries provide a convenient,injection free, process to build these objects. Consider the followingC++ example:

  1. BSONObj my_query = BSON( "name" << a_name );
  2. auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", my_query);

Here, my_query then will have a value such as { name : "Joe"}. If my_query contained special characters, for example,, :, and {, the query simply wouldn’t match anydocuments. For example, users cannot hijack a query and convert it toa delete.

JavaScript

Note

You can disable all server-side execution of JavaScript, by passing the—noscripting option on the commandline or setting security.javascriptEnabled in aconfiguration file.

All of the following MongoDB operations permit you to run arbitrary JavaScriptexpressions directly on the server:

You must exercise care in these cases to prevent users fromsubmitting malicious JavaScript.

Fortunately, you can express most queries in MongoDB withoutJavaScript and for queries that require JavaScript, you can mixJavaScript and non-JavaScript in a single query. Place all theuser-supplied fields directly in a BSON field and passJavaScript code to the $where field.

If you need to pass user-supplied values in a $where clause,you may escape these values with the CodeWScope mechanism. When youset user-submitted values as variables in the scope document, you canavoid evaluating them on the database server.