Documents & Types
Rules for documents that the OpenAPI types do not show.
Document ids
The _id of a document can have any type. In a request body, a string of 24 hexadecimal characters and {"$oid": "..."} are ObjectIds. Every other value (strings, numbers) is used as it is.
The id in the path of the single-document routes is a string. The server looks it up as an ObjectId (if it has that form), as the string itself, and, if it looks like a number (12345, 1.5), as a number too.
A filter can use ids as {"_id": "abc"}, {"_id": {"$in": ["abc", "507f1f77bcf86cd799439011"]}} or {"_id": {"$oid": "507f1f77bcf86cd799439011"}}.
Reading: Extended JSON
Routes that return documents (list, find, search, get, aggregate, and the json/ndjson export) take the query parameter extendedJson:
relaxed (default) | canonical | plain | |
|---|---|---|---|
| 32-bit integer | 5 | {"$numberInt": "5"} | 5 |
| 64-bit integer ≤ 2^53 | 5 | {"$numberLong": "5"} | 5 |
| 64-bit integer > 2^53 | {"$numberLong": "9007199254740993"} | the same | number (loses precision in JS) |
| double | 1.5 (2.0 is 2) | {"$numberDouble": "2.0"} | 1.5 |
| decimal | {"$numberDecimal": "10.25"} | the same | number |
| date | {"$date": "2024-06-15T12:00:00Z"} | {"$date": {"$numberLong": "1718452800000"}} | "2024-06-15T12:00:00Z" |
| ObjectId | {"$oid": "..."} | the same | hex string |
| text that looks like a date | {"$string": "2024-06-15T12:00:00Z"} | the same | the text |
| binary, timestamp, regex, min/max key | wrappers | the same | text forms |
What canonical returns can be written back as it is. The document in the database keeps the same types. With relaxed, whole numbers are written back as Int64.
A CSV export stays plain unless extendedJson is sent. Distinct values are plain unless extendedJson is sent (then an integer beyond 2^53 stays exact). File information, index and status maps, and the ids in insert and update responses are always plain strings.
The Nuxt module has helpers for these documents. See Extended JSON.
Expanding references
Since 2.4. For a declared collection with refs the read routes take expand (list, get, find, search, export, watch): ?expand=customerId&expand=tagIds or ?expand=customerId,tagIds; find, search and the export by body also take a body field expand: ["customerId"].
GET /mongodb/collections/orders/documents?expand=customerId[{ "_id": { "$oid": "…" }, "total": 12.5, "customerId": { "_id": { "$oid": "…" }, "name": "Ada" } }]The referenced documents are read with the caller's grant and read scope on their collection: one that cannot be read is null (left out of an array), never an error. At most 5 references; an unknown one, more than 5 or a csv export with expand answer 400.
Writing: dates and numbers in JSON bodies
A string in the body of an insert, update or filter is stored as a date if it is a full ISO-8601 instant: date, time with seconds, an optional fraction and a zone (Z or an offset).
| Value | Stored as |
|---|---|
"2024-06-15T12:00:00Z", "2024-06-15T12:00:00.000Z", "2024-06-15T14:00:00+02:00" | date |
"2024-06-15", "2024-06-15T12:00:00" (no zone), any other text | string |
{"$string": "2024-06-15T12:00:00Z"} | string |
12345678901234567 (JSON number that fits 64 bit) | 64-bit integer |
Writing: Extended JSON wrappers
A value gets its BSON type with an Extended JSON wrapper. This works in documents (insert, update, import), nested in objects and lists, in filter values ($in, $gt, ...) and as _id:
| Wrapper | Stored as |
|---|---|
{"$date": "2024-06-15T12:00:00Z"} | date (also epoch milliseconds or {"$numberLong": ...}) |
{"$numberLong": "9007199254740993"} | 64-bit integer |
{"$numberInt": "5"} | 32-bit integer |
{"$numberDouble": "1.5"} | double ("NaN", "Infinity", "-Infinity" allowed) |
{"$numberDecimal": "10.25"} | decimal128 |
{"$oid": "507f1f77bcf86cd799439011"} | ObjectId |
{"$binary": {"base64": "AQID", "subType": "00"}} | binary with sub type |
{"$uuid": "123e4567-e89b-12d3-a456-426614174000"} | binary sub type 4 |
{"$timestamp": {"t": 1700000000, "i": 1}} | timestamp |
{"$regularExpression": {"pattern": "^a", "options": "i"}} | regular expression |
{"$minKey": 1}, {"$maxKey": 1} | min / max key |
{"$string": "..."} | text, even if it looks like a date |
Only an object with exactly one of these keys is a wrapper. Any other object is a document. An invalid wrapper ({"$numberInt": "12.5"}, {"$oid": "xyz"}, {"$date": "yesterday"}) answers 400 naming the key, and nothing is stored. Wrappers are not read in aggregation pipelines.
Many-document routes
PUT .../documents/many/insertwith an empty list answers400. A duplicate_idanswers409, and the documents before it stay stored.- With
?ordered=falseevery document that can be stored is stored, and the others are listed so a retry can send exactly these:
{
"wasAcknowledged": true,
"insertedIds": ["u1", "u3", "u5"],
"insertedCount": 3,
"errors": [{ "index": 1, "code": 11000, "message": "E11000 duplicate key error, index: _id_" }]
}PATCH .../documents/many/updateandDELETE .../documents/many/deleterefuse an empty filter ({}) with400(code4003). SendmatchAll=trueif all documents are meant.- Both take either a MongoDB filter in the body or a Lucene
filterquery parameter (send{}as the body of a delete). Both at once is400(code4004), because a filter that is silently ignored would touch more documents than intended. - The answer of an update keeps the Scala contract:
upsertedIdsholds the id of the changed document, also when nothing was upserted ({"upsertedIds":["…"],"modifiedCount":1}). - In a versioned collection many-writes are not checked against the version, but count it up.
Partial updates
PATCH .../documents/{id}/partial merges plain fields into an explicit $set, so {"a": 1, "$inc": {"n": 1}} sets a and increments n.
Counting
GET .../documents/count?filter= answers { "count": n } for the documents that match the Lucene filter; POST .../documents/count takes { "filter": ... } in the body. A document whose _id is the string count cannot be fetched with GET .../documents/count; use the list with filter=_id:count.
Search in the request body
POST .../documents/search is the list with its parameters in the body, for filters that are too long for a URL:
{ "filter": "name:John AND age:[18 TO 65]", "sort": ["-age"], "projection": ["name", "age"] }Every field is optional. rowsPerPage and page stay query parameters. POST .../documents takes a MongoDB filter in the body instead.
The files of a bucket have the same (2.6): POST /mongodb/buckets/{bucket}/files/search with a Lucene filter on the fields of the files collection (filename:report*, metadata.year:2024, length:>1000), sort and projection in the body. GET …/files (JSON filter in the query) and POST …/files (MongoDB filter in the body) stay. PAGING_MAX_ROWS applies to all three.
The users collection
The document routes never answer the password field of the server's users collection (mc_users): list, find, search, get, export, aggregate (the pipeline starts with $unset of it) and distinct leave it out, and a projection that copies it under another name answers 400. They leave out apiKey the same way (USERS_READ_HIDE_API_KEY, 2.6; the default since 3.0, false keeps it readable). Manage users with the admin routes.
Live updates
Since 2.3 GET /mongodb/collections/{name}/documents/watch streams the changes of a collection as Server-Sent Events (read grant, optional Lucene filter):
| Event | Data | When |
|---|---|---|
upsert | { id, document } | a document is (now) in the scope: inserted, changed, back in the filter, restored |
remove | { id } | deleted, soft deleted, or changed so that it no longer matches |
reset | {} | the stream could not resume: load the list again |
The scope is the one of every read: the filter, the owner rule, soft delete and the document:beforeRead hooks of the app. Events come in the order of the changes and show the document as it is when they are sent: in a fast series of changes of one document an intermediate state can be skipped, the last event is always its current state.
The id of an event is a resume token: reconnect with the header Last-Event-ID to get what was missed. A comment every 25 seconds keeps proxies from closing the connection. Browsers use fetch (not EventSource) to send the bearer token; useMongocampLive does all of this.
Live updates need change streams: a replica set (a single node is enough) or a sharded cluster. On a standalone MongoDB the route answers 501 (code 5011). WATCH_MAX_STREAMS (default 100) limits the open streams of one instance (503 beyond).
# a single-node replica set for development
mongod --replSet rs0 --port 27018 --dbpath ./data/rs0
mongosh --port 27018 --eval "rs.initiate({ _id: 'rs0', members: [{ _id: 0, host: 'localhost:27018' }] })"
# NUXT_MONGOCAMP_SERVER_CONNECTION_URI=mongodb://localhost:27018/?replicaSet=rs0