A MongoDB server can host multiple independent databases. List the available databases on the server:
Connect to a database:
This is equivalent to the function:
Connecting to a Collection
A collection is a collection of documents. Getting a collection is the same getting a database:
The above syntax is equivalent to:
Note: databases and collections are created lazily, so getting a collection or database does not perform any operations on the MongoDB server. They are only created once the first document is inserted into them.
A Document in MongoDB can be viewed as a (possibly) nested Association whose keys must be strings and whose values are limited to a small set of types (for example, strings, lists, integers, dates, etc). One simple example of a document:
For a list available types that can be used as values, see the documentation for the "BSON" format.
Inserting a Single Document into a Collection
Insert the previous document into the "WolframTest" collection:
Get a list of the inserted document IDs:
Note: Every MongoDB document must have an "_id" key. If this key is missing from the document being inserted, it is automatically added to the document with value of type BSONObjectID.
A BSONObjectID object contains various metadata related to its creation:
Inserting Multiple Documents into a Collection
It is more efficient to insert many documents at once into a collection. Create a list of documents:
Insert these two documents into the collection:
Getting a Single Document
The simplest query is performed with MongoCollectionFindOne, which returns a single document from the collection:
We can specify that we want to find a document of a three year old cat:
Various keys that are not wanted can be eliminated using projection. Eliminating the "date" and "sex" fields:
This can be used to speed up the transfer of documents from the server, as unwanted parts of a document need not be transferred.
Note: for more information on building queries, the tutorial "Query Documents" from the MongoDB documentation might be useful.