CodeNewbie Community

loading...

How to insert a single document into a MongoDB collection

Donald Feury
Appalachian Boi
Originally published at donaldfeury.xyz on ・1 min read

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Discussion (0)