Robert Mrobo
Robert Mrobo

Reputation: 138

How to write the Cosmos DB query with a 'in' keyword using LINQ?

I have this sample document in my azure cosmos db database.

{
    "partitionKey": "SonicTag",
    "label": "SonicTag",
    "name": "Kasi Tournaments",
    "slug": "kasi-tournaments",
    "a2AQuestionsCount": 0,
    "iconUrl": null,
    "id": "1af53736-c492-40bf-8ef7-dba2d17f6c17"
}

when I run the following query on the Data Explorer, I get exactly what I want (3 documents which has the specified IDs).

SELECT * FROM c where c.id in 
   ("dc4201ff-35b8-4eda-b0a6-f9bc2bb93926",
    "3389f2f2-33f3-4b08-8d32-4602071eae30",
    "1af53736-c492-40bf-8ef7-dba2d17f6c17")
and c.partitionKey = "SonicTag"

Just for example, on one my queries, where I'm looking for all the tags, I can use the following code.

    var feedIterator = Container.GetItemLinqQueryable<SonicTag>(true)
        .Where(c => c.PartitionKey == nameof(SonicTag)
                    && c.Label == nameof(SonicTag)).ToFeedIterator();

But I have no idea how can I write my LINQ to get al

Please note, on the method where I have to construct this LINQ, I receive a List of IDs and I must get all the Tags which have those Ids. The parameter is guaranteed that it will only contain a maximum of 5 IDs.

In the meantime, I using what is obviously a bad workaround of

var tags = new List<SonicTags>();
foreach (var id in IDs)
{
    tags.Add( Helper.ConvertStreamToObject( await Container.ReadItemStreamAsync(id, partitionKey)));
}

Upvotes: 0

Views: 2606

Answers (2)

Robert Mrobo
Robert Mrobo

Reputation: 138

I have found a solution by using the Contains method of List<T>. Below is my method.

public async Task<List<SonicTag>> GetTagsAsync(List<string> ids)
{
    var feedIterator = 
        Container.GetItemLinqQueryable<SonicTag>()
            .Where(x=> ids.Contains(x.Id)).ToFeedIterator();

    var tags = new List<SonicTag>();
    while (feedIterator.HasMoreResults)
    {
        var res = await feedIterator.ReadNextAsync();
        tags.AddRange(res.ToList());
    }

    return tags ;
}

Upvotes: 2

Mike Ubezzi
Mike Ubezzi

Reputation: 1027

Please take a look at the following LINQ to SQL translation document which will help you construct the correct expression. An example:

Where Operator, example #2"

LINQ lambda expression

input.Where(
    family => family.parents[0].familyName == "Wakefield" &&
    family.children[0].grade < 3);

SQL

SELECT *
FROM Families f
WHERE f.parents[0].familyName = "Wakefield"
AND f.children[0].grade < 3

Upvotes: -1

Related Questions