Nik
Nik

Reputation: 9452

MongoDB: does it make any sense to `find` a document by `_id` after it was `inserted`?

I wonder if there is any benefit in fetching a document by its _id after it was inserted into the database. Currently, I do this for all insertions. All ObjectId values are generated on the server and they are unique.

I wonder if I could save some time by not doing find after insert? Will this have any negative consequences? Assuming that insert will throw an error in case of failure.

Current code (Haskell/pseudocode - these snippets are not language specific):

createAccount :: String -> String -> IO (Maybe Document)
createAccount email password = do
    -- Prepare document
    -- create `user` subdocument with a unique random ObjectId generated by the library
    -- create `account` document with a unique random ObjectId generated by the library
    user <- liftIO(createUser email password)
    account <- liftIO(Model_Account.create user)

    -- Convert local object to BSON, insert document, obtain _id 
    accountId <- run(insert collection (toBSON account))

    -- Look up and return newly inserted document
    run(findOne(select ["_id" =: accountId] collection))

Alternative:

createAccount :: String -> String -> IO Document
createAccount email password = do
    -- Prepare document
    -- create `user` subdocument with a unique random ObjectId generated by the library
    -- create `account` document with a unique random ObjectId generated by the library
    user <- liftIO(createUser email password)
    account <- liftIO(Model_Account.create user)

    -- Convert local object to BOSN, insert account, ignore `_id` returned by the database server
    _ <- run(insert collection(toBSON account))

    -- Return "local" version of the document
    return account

Thanks!

Upvotes: 0

Views: 99

Answers (2)

Simon Jacobs
Simon Jacobs

Reputation: 6588

MongoDB both returns the _id and confirms success when you insert a document, so it's not necessary to query the database for either of those reasons (documentation).

Doing that at scale would put extra load on and slow down your application so it's best avoided. Use the information the database returns to update your application state and move on.

Upvotes: 1

Niraj Patel
Niraj Patel

Reputation: 810

In NODEJS, Usually we create request to save data and then wait for insertion.

-> On Successful insertion, we get inserted data. Hence I believe there is no need to find data by Id as you will usually get that in return of success.

-> On Error, we get the reason for error.

Upvotes: 1

Related Questions