Search code examples
javascriptnode.jsazure-functionsazure-cosmosdbazure-cosmosdb-sqlapi

Cosmos DB NoSQL (NodeJS/Javascript): How to readAll() but for specific attributes only? Not the entire object


Let's say I have below documents inside my Cosmos DB (NoSQL) container:

[
  {
    "id": "isaacnewton",
    "fullname": "Isaac Newton",
    "dob": "04011643",
    "country": "United Kingdom"
  },
  {
    "id": "alberteinstein",
    "fullname": "Albert Einstein",
    "dob": "14031879",
    "country": "Germany"
  },
  ...
]

Say, I have like about 10000 of them.

In order to read all the documents from the container, currently I know the basic usage of readAll(), which is:

const { resources: allItems } = await container.items.readAll().fetchAll();

But it returns all the attributes/fields from the documents (objects). Even the unwanted system attributes like _rid, _self, _etag, etc are there in the response.

Question

While using the readAll() function, not the query() function, how do I specify which certain attributes/fields that I want in the response? Can I only receive "id" and "fullname" only?

Expecting the outcome to be like this:

[
  {
    "id": "isaacnewton",
    "fullname": "Isaac Newton"
  },
  {
    "id": "alberteinstein",
    "fullname": "Albert Einstein"
  },
  ...
]

Solution

  • There are three fundamental ways to retrieve documents from a container:

    • Read a single document from a container (providing the document's ID and partition-key value). This always returns all properties.
    • Query a container for documents (with a SQL query, along with either a partition-key value or a cross-partition query signal, and optionally max # of documents to return). You get to choose which properties you want.
    • Read "all documents" from a container (you may optionally limit this by specifying max # of documents). Just like a single-read, this returns full documents with all properties, but as an array of documents.

    Your call to ReadAll() is going to return you an array of documents, with every property of those documents.

    The only way to filter properties for your returned documents is with a query; there's no ability to do this for a single read, or for a read-all-documents operation (you can even look at the underlying get a document and list documents REST API details, which is what Read() and ReadAll() ultimately map to).

    Ok, there is one more approach: you can do property-filtering client-side after returning an array of documents, but you will still be transmitting full documents from Cosmos DB to your client application.