I'm playing around on https://www.documentdb.com/sql/demo, which allows me to query against sample documents that look like:
{
"id": "19015",
"description": "Snacks, granola bars, hard, plain",
"tags": [
{
"name": "snacks"
}
],
"version": 1,
"isFromSurvey": false,
"foodGroup": "Snacks",
"servings": [
{
"amount": 1,
"description": "bar",
"weightInGrams": 21
}
]
}
I'm confused about ARRAY_CONTAINS()
. This query returns results:
SELECT root
FROM root
WHERE ARRAY_CONTAINS(root.tags, { "name": "snacks" })
However, this query does not:
SELECT root
FROM root
WHERE ARRAY_CONTAINS(root.servings, { "description": "bar" })
What gives?
What I'm trying to achieve is illustrated by how I would write the query if this was C#:
var filteredDocs = docs.Where(d => d.Servings != null &&
d.Servings.Length > 0 &&
d.Servings.Any(s => s.Description == "bar"));
It appears the first example query on root.tags
works because { "name": "snacks" }
is the entire object in the root.tags
array, while, in the second query, { "description": "bar" }
is only one field in the root.servings
objects.
How can I modify the second query on root.servings
to work with only knowing the serving description
?
Not sure if this functionality was available when you were looking at the API originally but the ARRAY_CONTAINS now supports an optional Boolean value at the end to provide partial match support.
SELECT root
FROM root
WHERE ARRAY_CONTAINS(root.servings, { "description": "bar" }, true)
Here is sample using the documentdb demo site that queries an array that contains multiple fields for each object stored.
SELECT *
FROM food as f
WHERE ARRAY_CONTAINS(f.servings, {"description":"bar"}, true)