Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last inserted id using the JS api?

Tags:

mongodb

Using the javascript api for MongoDB, how do you get the ID of the last inserted object? i.e.

obj = {a: 1, b: 2};
db.foo.insert(obj);

How do I get the ID for obj?

like image 214
Allen Rohner Avatar asked Aug 31 '10 16:08

Allen Rohner


People also ask

How can I get last INSERT ID in firebase?

To be able to get the id try the following: const ref = db. ref("xpertz_organization/" + user_id); const organization_id = ref. push().

How can I get recently inserted ID in SQL?

The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How do I find the last inserted record id?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.


2 Answers

The people on #mongodb were helpful. The JS API doesn't currently support this, but you can use your own id. To generate a "normal" id, do _id: new ObjectId(). So the example in my question would be:

id = new ObjectId();
obj = {a: 1, b: 2, _id: id};
db.foo.insert(obj);
like image 139
Allen Rohner Avatar answered Oct 08 '22 21:10

Allen Rohner


If you run

db.collection("venues").insert( {name: "test3", FSid: "test3"}, function( err, ret) {
   console.log( ret )
})

it returns

{ result: { ok: 1, n: 1 },
  ops: [ { name: 'test3', FSid: 'test3', _id: 57cb0a1162cecfe636df6fc1 } ],
  insertedCount: 1,
  insertedIds: [ 57cb0a1162cecfe636df6fc1 ] }

So you can get your ids along with all inserted objects through:

ret.ops[0]._id

or straight

ret.insertedIds[0]
like image 21
Nico Avatar answered Oct 08 '22 21:10

Nico