Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query in DocumentDB based on inner json object value?

Suppose I have 3 objects in DocumentDB like this.

This is the class record.

And now I want to get all the Id's where a student exist with name sunny.

{
  "id": "111",
  "class": 1,
  "students": [
    {
      "name": "sunny"
    },
    {
      "name": "pinki"
    },
    {
      "name": "bobby"
    },
    {
      "name": "lucky"
    }
  ]
}

{
  "id": "222",
  "class": 2,
  "students": [
    {
      "name": "pinki"
    },
    {
      "name": "sunny"
    },
    {
      "name": "bobby"
    }
  ]
}

{
  "id": "333",
  "class": 3,
  "students": [
    {
      "name": "pinki"
    },
    {
      "name": "lucky"
    },
    {
      "name": "bobby"
    }
  ]
}

What will be the query to get the result?

like image 702
satish kumar V Avatar asked Mar 11 '15 11:03

satish kumar V


1 Answers

You can use DocumentDB's JOIN to create a cross product on documents with array elements.

For example, the following query creates a cross-product on documents with it's students property to query on the students.name:

select doc.id
from doc
join students in doc.students
where students.name = 'sunny'

returns the following dataset:

[{
    id: 111
}, {
    id: 222
}]

Reference: http://azure.microsoft.com/en-us/documentation/articles/documentdb-sql-query/#joins

like image 80
Andrew Liu Avatar answered Oct 18 '22 14:10

Andrew Liu