nagaraja
nagaraja

Reputation: 51

How to query on cosmos database using CreateDocumentQuery in C#

I have the following 2 rows of json data stored as a 2 documents in cosmos db:

{
 "Lists": [ 
   {
      "number":"1", 
      "Name": "Doctor"
   },
   {
      "number":"2",
      "Name": "Lawyer"
   }
 ],
 "Brands": [18,25],                                                
 "type":"Msg"

}

{
 "Lists": [ 
    {
      "number":"3", 
      "Name": "Engineer"
    },
    {
      "number":"4",
      "Name":"Labour"
    }
 ],     
 "Brands": [16,27],
 "type": "Call"
}

How to query to cosmos db collection to filter such that Brands.Contains(16) && Lists.number.Contains(3) i:e 2nd row in the above json. I want to achieve this with help of JObject or any other logic so that without creating a Model Class for the above json I can filter the collection.

Below is the Query logic but how to write the above filter in this below IDocumentQuery?

IDocumentQuery<JObject> query = client.CreateDocumentQuery<JObject>(
            UriFactory.CreateDocumentCollectionUri(Constants.C4CosmosDatabaseId, collectionId),
            _feedOptions)
            .AsDocumentQuery();

Upvotes: 1

Views: 2002

Answers (1)

Roman Marusyk
Roman Marusyk

Reputation: 24579

If you use Microsoft.Azure.Cosmos Version="3.19.0", then try

string number = "3";
int brand = 16;

var query = $"SELECT c.Lists, c.Brands FROM c JOIN t IN c.Lists WHERE CONTAINS(t.number, {number}, false) and ARRAY_CONTAINS(c.Brands, {brand }, false)";

FeedResponse<JObject> response = await _container
   .GetItemQueryIterator<JObject>(new QueryDefinition(query))
   .ReadNextAsync();

Upvotes: 1

Related Questions