Sign In Register

How can we help you today?

Start a new topic
Answered

Get ID of last inserted record in NoSQL

If I do a .insert on a collection in Cloud code, how can I get the _id value of the document I just inserted?  


There seems to be a way of doing it in MongoDB generally, but I can't work out how to do it from the Spark interfaces


Cheers,

Fred


Best Answer

Hi Fred,


The object you are inserting into the Collection will be updated to include the document's Id, for example:


  

var col = Spark.runtimeCollection("testDB");

var docToInsert = {"test1":"1", "test2":"t"}; //Has no $oid 

var insertedDoc = col.insert(docToInsert);

Spark.setScriptData("insertedDocId", docToInsert._id.$oid); //If the insertion was successful it should now have an $oid

  

Here's the response to running that script:


 

{
 "@class": ".LogEventResponse",
 "scriptData": {
  "insertedDoc": "54da0481e4b021c1875a5b64"
 }
}

 

Shane


Answer

Hi Fred,


The object you are inserting into the Collection will be updated to include the document's Id, for example:


  

var col = Spark.runtimeCollection("testDB");

var docToInsert = {"test1":"1", "test2":"t"}; //Has no $oid 

var insertedDoc = col.insert(docToInsert);

Spark.setScriptData("insertedDocId", docToInsert._id.$oid); //If the insertion was successful it should now have an $oid

  

Here's the response to running that script:


 

{
 "@class": ".LogEventResponse",
 "scriptData": {
  "insertedDoc": "54da0481e4b021c1875a5b64"
 }
}

 

Shane


1 person likes this

Brilliant - will give this a try, thanks

Has this changed? Insert seems to return true or false now. 

 Hi Barry,


The insert operation returns true or false depending on whether it has succeeded or not. It's the scriptData line that's returning the value, specifically "docToInsert._id.$oid".


Regards,

Liam

Login to post a comment