How can I obtain a document from a Cosmos DB using a field in an array as a filter?

Viewed 27

I have a Cosmos DB with documents that look like the following:

{
  "name": {
      "productName": "someProductName"
  },
  "identifiers": [
     {
         "identifierCode": "1234",
         "identifierLabel": "someLabel1"
     },
     {
         "identifierCode": "432",
         "identifierLabel": "someLabel2"
     }
  ]
}

I would like to write a sql query to obtain an entire document using "identifierLabel" as a filter when searching for the document.

I attempted to write a query based on an example I found from the following blog:

SELECT c,t AS identifiers
FROM c
JOIN t in c.identifiers
WHERE t.identifierLabel = "someLabel2"

However, when the result is returned, it appends the following to the end of the document:

{
  "name": {
      "productName": "someProductName"
  },
  "identifiers": [
     {
         "identifierCode": "1234",
         "identifierLabel": "someLabel1"
     },
     {
         "identifierCode": "432",
         "identifierLabel": "someLabel2"
     }
  ]
},
{
         "identifierCode": "432",
         "identifierLabel": "someLabel2"
}

How can I avoid this and get the result that I desire, i.e. the entire document with nothing appended to it?

Thanks in advance.

1 Answers

Using ARRAY_CONTAINS(), you should be able to do something like this to retrieve the entire document, without any need for a self-join:

SELECT *
FROM c
where ARRAY_CONTAINS(c.identifiers, {"identifierLabel":"someLabel2"}, true)

Note that ARRAY_CONTAINS() can search for either scalar values or objects. By specifying true as the third parameter, it signifies searching through objects. So, in the above query, it's searching all objects in the array where identifierLabel is set to "someLabel2" (and then it should be returning the original document, unchanged, avoiding the issue you ran into with the self-join).

Related