What is a MongoDB ObjectId?

An ObjectId is the ID that MongoDB gives each document by default, in its _id field. It's 12 bytes long and written as 24 hexadecimal digits, each from 0 to 9 or a to f. The first eight digits are the time the ID was made, in seconds since 1970, the next ten are a random value that each running program picks once, and the last six are a counter. Since the time comes first, IDs sort roughly by when they were made. The MongoDB shell shows an ID wrapped as ObjectId("..."), and Extended JSON as {"$oid": "..."}.

You meet ObjectIds in web addresses such as /orders/ followed by an ID, in API requests and responses, in logs and in database tools. Developers check one before they run a query with it, because many MongoDB libraries throw an error for a malformed ID instead of simply finding nothing.

Tool description

Type or paste an ID into the MongoDB ObjectId field, and the result shows as you type: "MongoDB ObjectId is valid" or "MongoDB ObjectId is not valid". Spaces and line breaks around a pasted ID are ignored. The page has no settings.

IDs that pass

  • Exactly 24 hexadecimal digits
  • Small letters, capital letters or a mix: MongoDB prints them small, but its drivers read both
  • Any 24 digits at all, since the check doesn't read the time inside

IDs that fail

  • 23 or 25 digits: one too few or one too many
  • Any letter after f, or a space, hyphen or quote inside
  • The ObjectId("...") wrapper of the shell or the {"$oid": ...} form of Extended JSON: copy only the 24 digits between the quotes

Good to know

  • The check looks at the form only. It can't tell whether a document with that ID exists in any database.
  • A quirk of the library: 0x or 0h followed by 22 digits passes, because the check counts the prefix as two of the 24 characters. MongoDB doesn't accept such an ID, and 0x followed by all 24 digits fails here.
  • To see when an ID was made, use the MongoDB ObjectId Date Extractor. For IDs to test with, use the Random MongoDB ObjectId generator.

Features

  • Checks MongoDB ObjectIds as you type
  • 24 hexadecimal digits, in small or capital letters
  • Ignores spaces and line breaks around a pasted ID
  • Runs in your browser, so nothing you type is sent anywhere