skip to Main Content

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"
  },
  ...
]

2

Answers


  1. You should be able to achieve this by using the fetchAll if you are using the latest package,

    const { resources } = await container.items
      .query("SELECT c.id, c.fullname from c")
      .fetchAll();
    
    Login or Signup to reply.
  2. Thanks Sajeetharan for the answer. Posting a different approach to get expected output.

    ReadAll() method reads the entire document.

    Approach 1

    You can use for loop to fetch specific properties from the output of ReadAll() method.

    Below is sample code – (Here I have declared two variables id and name and assigned their values inside for loop).

    const { resources } = await  container.items.readAll().fetchAll();
    
    var  id, name ;
    
    for (const  item  of  resources) {
    id = item.id;
    name = item.fullname;
    console.log(`${item.id}: ${item.name}`);
    }
    

    Approach 2

    You can make use of Cosmos DB like query and to read items you can use fetchAll() method.

    Here is sample code

    const  querySpec = {
    query:  "select p.id, p.fullname from p"
    };
    

    If you want to filter the data, you can use parameterize query.
    sample code below.

    const  querySpec = {
    query: "select p.fullname, p.id from p where p.country=@country",
    parameters: [
    {
    name: "@country",
    value: "Germany"
    }
    ]
    }; 
    

    And below code is to read the selected items.

    const { resources } = await  container.items.query(querySpec).fetchAll();
    for (const  item  of  resources) {
    console.log(`${item.id}: ${item.fullname}`);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search