1 min read

How to insert a single document into a MongoDB collection

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"
})

Did you find this information useful? If so, consider heading over to my donation page and drop me some support.

Want to ask a question or just chat? Contact me here