MongoDB version: 5.0.9+ - Date: June 2022
Main concepts
Document : A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are very similar to JSON objects. Values may include other documents, arrays, and arrays of documents.
{
name: "John",
age: 77,
nets: [ "expert", "developer", "superhero" ],
lastExp: { name: "Full-Stack Lead Developer", duration: 10.5 }
}
Note : each document requires a unique _id field (uses the ObjectId BSON type) that acts as a primary key. The MongoDB driver generates it if omitted.
Collection : A grouping of MongoDB documents. A collection is the equivalent of an RDBMS table. Collections do not enforce a schema by default. Documents within a collection can have different fields but should have a similar or related purpose.
BSON types
Each value of a field/value pair is recorded as a BSON type. BSON is a binary serialization format. The most used and useful BSON types in MongoDB are (each BSON type has both integer and string identifiers) :
Double : 1 "double" ; String : 2 "string" ; Object : 3 "object" ; Array : 4 "array" ; ObjectId : 7 "objectId" ; Boolean : 8 "bool" ; Date : 9 "date" ; Null : 10 "null" ; 32-bit integer : 16 "int" ; 64-bit integer : 18 "long" ; Decimal128 : 19 "decimal"
Note : Timestamp data type is for internal MongoDB use. You will want to use the BSON date type.
Time series collections
Time series collections came with version 5.0 of MongoDB. They efficiently store sequences of measurements over a period of time. Time series data is any data that is collected over time and is uniquely identified by one or more unchanging parameters. Consider using them for measurements storage !
CRUD Operations
Create
db.collection.insertOne()
db.collection.insertMany()
db.users.insertOne(
{ name: "John", surname: "Doe" }
)
db.users.insertMany(
{ name: "John", surname: "Doe" },
{ name: "Jean", surname: "Dudule" }
)
Note : If the collection does not currently exist, insert operations will create the collection.
Find (see Query operators)
db.collection.find()
db.users.find(
{ age: { $gt: 18 } }
)
Update (see Query/Update operators)
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
db.users.updateMany(
{ age: { $gt: 60 } },
{ $set: { retirement: true } }
)
See findAndModify to modify and return a single document. By default, the returned document does not include the modifications made on the update.
Delete
db.collection.deleteOne()
db.collection.deleteMany()
db.users.deleteMany(
{ retirement: true }
)