📜  mongodb insertone (1)

📅  最后修改于: 2023-12-03 15:32:56.566000             🧑  作者: Mango

MongoDB insertOne()

The MongoDB insertOne() method is used to insert a single document into a collection in the MongoDB database. It takes two arguments:

  • A document object to insert. This object should be a dictionary-like object that represents the data to be inserted.
  • An optional callback function that will be called once the operation completes.

The insertOne() method is an asynchronous operation that returns a Promise. The Promise resolves with an object that contains an acknowledged property set to true if the document was successfully inserted into the collection, and a insertedId property that stores the _id value of the inserted document.

Syntax

The syntax for the insertOne() method is as follows:

db.collection.insertOne(document, options, callback)
  • db.collection is the name of the MongoDB collection you want to insert the document into.
  • document is a JavaScript object that represents the document you want to insert.
  • options is an optional object that can be used to specify additional options for the insert operation.
  • callback is an optional function that will be called when the operation completes.
Example

Here's an example that shows how to use the insertOne() method to insert a document into a collection:

const MongoClient = require('mongodb').MongoClient;

const uri = 'mongodb://localhost:27017/test';
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect((err) => {
  const collection = client.db('test').collection('users');
  const doc = { name: 'John Doe', email: 'johndoe@example.com' };
  collection.insertOne(doc, (err, result) => {
    if (err) {
      console.error(err);
    } else {
      console.log(`Inserted document with id ${result.insertedId}`);
    }
    client.close();
  });
});

In this example, we first create a new MongoClient instance and connect to a test database running on localhost:27017. We then get a handle to the users collection and create a new document with the fields name and email. Finally, we call the insertOne() method to insert the document into the collection, and log the inserted document's _id value to the console.

Conclusion

The insertOne() method is a powerful tool for inserting documents into a MongoDB collection, and its simplicity makes it easy to use in your Node.js applications. By following the examples provided above, you can quickly and easily start using the insertOne() method in your own MongoDB projects.