MongoDB Documentation, Release 3.0.4 var cursor = targetCollection.find( {}, { _id: 1 } ).sort( { _id: -1 } ).limit( 1); var seq = cursor.hasNext() ? cursor.next()._id + 1 : 1; doc._id = seq; var results = targetCollection.insert(doc); if ( results.hasWriteError() ) { if ( results.writeError.code == 11000 / * dup key * / ) continue ; else print( "unexpected error inserting data: " + tojson( results ) ); } break ; } } The while (1) loop performs the following actions: • Queries the targetCollection for the document with the maximum _id value. • Determines the next sequence value for _id by: – adding 1 to the returned _id value if the returned cursor points to a document. – otherwise: it sets the next sequence value to 1 if the returned cursor points to no document. • For the doc to insert, set its _id field to the calculated sequence value seq . • Insert the doc into the targetCollection . • If the insert operation errors with duplicate key, repeat the loop. Otherwise, if the insert operation encoun- ters some other error or if the operation succeeds, break out of the loop. 2. Use the insertDocument() function to perform an insert: var myCollection = db.users2; insertDocument( { name: "Grace H." }, myCollection ); insertDocument( { name: "Ted R." }, myCollection ) You can verify the results with find() : db.users2.find() The _id fields contain incrementing sequence values: Chapter 3. MongoDB CRUD Operations 128