@wilmer.lemke
To get the _id
of the inserted document in MongoDB, you can use the insertOne()
or insertMany()
method, which returns an object containing the _id
of the inserted document(s).
Here is an example of how to use the insertOne()
method to insert a new document into a collection and get its _id
:
1 2 3 4 5 6 7 8 9 10 11 |
const MongoClient = require('mongodb').MongoClient; const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority"; const client = new MongoClient(uri, { useNewUrlParser: true }); client.connect(err => { const collection = client.db("test").collection("devices"); // Insert a single document collection.insertOne({ name: "Apple iPhone X" }, (err, result) => { console.log(result.insertedId); client.close(); }); }); |
The insertedId
field of the result
object returned by the insertOne()
method contains the _id
of the inserted document.
You can use the insertMany()
method in a similar way to insert multiple documents and get their _id
s. The insertedIds
field of the result
object returned by the insertMany()
method contains an array of the _id
s of the inserted documents.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const MongoClient = require('mongodb').MongoClient; const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority"; const client = new MongoClient(uri, { useNewUrlParser: true }); client.connect(err => { const collection = client.db("test").collection("devices"); // Insert multiple documents collection.insertMany([ { name: "Apple iPhone X" }, { name: "Google Pixel 3" }, { name: "OnePlus 6T" } ], (err, result) => { console.log(result.insertedIds); client.close(); }); }); |
Note that the _id
field is automatically generated by MongoDB if you don't specify a value for it when inserting a new document. The _id
field is a unique identifier for each document in a collection and is used to distinguish documents from one another.