For a full overview of MongoDB and all my posts on it, check out my overview.
MongoDB has several ways of inserting documents into collections. The main way is using a method on collections called insert.
Here is an example:
// Let's say we want to insert a new document representing a new user
db.users.insert({
email: "test@test.com",
username: "test_user",
password: "please encrypt your passwords"
})
This will insert our "user" document into the users collection. We don't even have to make sure the users collection already exists since collections in MongoDB are automatically created during inserts. You can insert many documents at one time into a MongoDB collection using the insert
method as well.
More recent versions of MongoDB will give you a deprecation warning when using insert
and will instead want you to use insertOne
for inserting single documents.
db.users.insertOne({
email: "test@test.com",
username: "test_user",
password: "please encrypt your passwords"
})
Top comments (0)