Docs Menu

Insert a Document

Note

If you specify a callback method, insertOne() returns nothing. If you do not specify one, this method returns a Promise that resolves to the result object when it completes. See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.

You can insert a document into a collection using the collection.insertOne() method. To insert a document, define an object that contains the fields and values that you want to store. If the specified collection does not exist, the insertOne() method creates the collection.

You can specify additional query options using the options parameter. For more information on the method parameters, see the insertOne() API documentation. You can also pass a callback method as an optional third parameter. For more information on this method, see the insertOne() API documentation.

If the operation successfully inserts a document, it appends an insertedId field to the object passed in the method call, and sets the value of the field to the _id of the inserted document.

Note

You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.

If you run the preceding example, you should see the following output:

A document was inserted with the _id: <your _id value>
←  Insert OperationsInsert Multiple Documents →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.