0

I've searched around to see if anybody needed this before but couldn't find much.

I have the following json objects in Azure DocumentDB collection:

{
    personID: 1,
    name: "Bruce",
    surname: "Dickinson",
    items: [
        {
            itemID: 1,
            itemType: "A",
            name: 'Item 1'
        },
        {
            itemID: 2,
            itemType: "A",
            name: 'Item 2'
        },
        {
            itemID: 3,
            itemType: "B",
            name: 'Item 3'
        }
    ]

}

The collection has many Persons in it. personID 2, 3, 4 ......100....1000 and so on.

I would like to write a SQL query to extract an array of itemIDs for personID = 1 and items with itemType = 'A'. I want the result to look like this:

itemIDs: [
    1,
    2
]

or simply:

[
    1,
    2
]

Has anybody ever tried doing this before? Is it even possible?

1 Answer 1

1

Someone with more SQL foo than me might know a way to do it with just SQL, but I would use a user-defined function (UDF) to do it.

Here is the SQL:

SELECT VALUE udf.getItemIDArray(c) FROM collection c WHERE <your clause>

Here's what the UDF might look like:

function getItemIDArray (o) {
  output = [];
  for (item in o.items) {
    output.push(item.itemID)
  }
  return output 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Mmmm interesting. Thanks for that. The output.push(item.itemID) seems to be pushing a null instead of the item.itemID. Why would that be you think?
Hmm try putting a "var" in front of "for (var item in o.items)"
Still did not work. I am doing it in the application for the time being but would like to do it at the db level to transport less over the network.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.