Find documents (C#)

Finds documents in a collection using filter and sort clauses, including vector search.

To find documents with hybrid search, see Find and rerank documents (C#).

If you add or remove documents after starting the operation, the result might not reflect real-time changes in the data.

Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart.

Result

Returns a CollectionFindCursor object that supports fluent chaining of options to modify the Find operation. This object implements IEnumerable and IAsyncEnumerable to iterate over the found documents.

The fields included in the returned documents depend on the subset of fields that were requested in the projection.

If requested and applicable, each document will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the document’s vector.

If requested when executing a vector search, the result will also include the sort vector. You can access the sort vector by using the GetSortVector() on the result.

You must iterate over the cursor to fetch matching documents. For details about iteration, see Iterate over found documents.

Parameters

Use the Find method, which belongs to the Collection class.

Method signature
public CollectionFindCursor<T> Find(
  CollectionFilter<T> filter, CollectionFindOptions<T> options = null
);
public CollectionFindCursor<T> Find(
  CollectionFindOptions<T> options = null
);
Name Type Summary

filter

CollectionFilter

An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria. Filters can improve performance by reducing the number of documents that the Data API processes.

You must use & to escape any . or & in field names in the filter clause. You cannot use & to escape any other characters. For more information, see Work with . and & in field names (C#).

For a list of available filter operators and more examples, see Filter operators for collections (C#).

Filters can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in a filter.

For an example, see Use filters to find documents.

options

CollectionFindOptions

Optional. Options for this operation. For more information and examples for general options such as timeout, see Customize API interaction. For options specific to this method, see Method-specific properties of the CollectionFindOptions class.

Method-specific properties of the CollectionFindOptions class
Name Type Summary

Projection

IProjectionBuilder

Optional. Controls which fields are included or excluded in the returned document.

You must use & to escape any . or & in field names in the projection clause. You cannot use & to escape any other characters. For more information, see Work with . and & in field names (C#).

For more information, see Projections for collections (C#).

Default: The default projection for the collection. All fields prefixed with $ are excluded by default and will only be returned if you include them in the projection. _id is included by default and will always be returned unless you exclude it from the projection.

IncludeSimilarity

bool

Optional. Whether to include a $similarity property in the response.

The $similarity value represents the closeness of the sort vector and the document’s vector.

This parameter only applies if you use a vector search.

Default: false

IncludeSortVector

bool

Optional. Whether to include the sort vector in the response.

This can be useful if you do a vector search with $vectorize, since you don’t know the sort vector in advance.

Because vector search is approximate, setting a lower limit increases the chance of finding a close match, but not necessarily the best match.

This parameter only applies if you use a vector search.

Default: false

Sort

SortBuilder<T>

Optional. Sorts documents by one or more fields, or performs a vector search.

You must use & to escape any . or & in field names in the sort clause. You cannot use & to escape any other characters. For more information, see Work with . and & in field names (C#).

For more information, see Sort clauses for collections (C#).

Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries.

For vector searches, this parameter can use either $vector or $vectorize.

Skip

int

Optional. The number of documents to bypass (skip) before returning documents.

The API excludes the first n documents matching the query, and the results begin at the n+1 document.

This parameter only applies if you also explicitly specify an ascending or descending sort criterion. This parameter is not valid with vector search.

For an example, see Skip documents.

Limit

int

Optional. Limit the total number of documents returned. Once limit is reached, or the cursor is exhausted due to lack of matching documents, nothing more is returned.

For vector search, a lower limit reduces the accuracy of the search and the time required for the search.

InitialPageState

string

Optional. The nextPageState value from the response of fetchNextPage() called on a previous cursor.

Used to manually request the next page of results. This is useful for cases where an external action triggers fetching the next page of results.

For an example, see Iterate over found documents.

Examples

The following examples demonstrate how to find documents in a collection.

Use filters to find documents

You can use a filter to find documents that match specific criteria. For example, you can find documents with an is_checked_out value of false and a number_of_pages value less than 300.

For a list of available filter operators and more examples, see Filter operators for collections (C#).

Filters can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in a filter.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.And(
      filterBuilder.Eq("is_checked_out", false),
      filterBuilder.Lt("number_of_pages", 300)
    );

    var result = collection.Find(filter);

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Use vector search to find documents

To find the documents whose $vector value is most similar to a given vector, use a sort with the vector embeddings that you want to match. For more information, see Find data with vector search.

Vector search is only available for vector-enabled collections. For more information, see Create a collection that can store vector embeddings and $vector in collections (C#).

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var embeddings = new float[] { 0.08f, -0.62f, 0.39f };
    var result = collection.Find(
      new CollectionFindOptions<Document>()
      {
        Sort = Builders<Document>.CollectionSort.Vector(embeddings),
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Use vector search and vectorize to find documents

To find the document whose $vector value is most similar to the $vector value of a given search string, use a sort with the search string that you want to vectorize and match. For more information, see Find data with vector search.

Vector search with vectorize is only available for collections that have vectorize enabled. For more information, see Create a collection that can automatically generate vector embeddings and $vectorize in collections (C#).

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var result = collection.Find(
      new CollectionFindOptions<Document>()
      {
        Sort = Builders<Document>.CollectionSort.Vectorize(
          "Text to vectorize"
        ),
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Use lexicographical matching to find documents

Lexicographical matching is currently in public preview. Development is ongoing, and the features and functionality are subject to change. Astra DB Serverless, and the use of such, is subject to the DataStax Preview Terms.

There are two ways to use lexicographical matching to find documents with the Data API:

You can use these strategies together or separately.

You can only use lexicographical matching on collections that have lexical enabled. For more information, see Create a collection that supports lexicographical matching.

Documents must have the $lexical field populated to be included in lexicographical matching. For examples, see Insert a document for retrieval with lexicographical matching and Insert documents for retrieval with lexicographical matching.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filter = Builders<Document>.CollectionFilter.LexicalMatch(
      "tree hill"
    );

    var sort = Builders<Document>.CollectionSort.Lexical(
      "tree hill grassy"
    );

    var result = collection.Find(
      filter,
      new CollectionFindOptions<Document>() { Sort = sort }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Use sorting to find documents

You can use a sort clause to sort documents by one or more fields.

For more information, see Sort clauses for collections (C#).

Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var sort = Builders<Document>
      .CollectionSort.Ascending("rating")
      .Descending("title");
    var result = collection.Find(
      new CollectionFindOptions<Document>() { Sort = sort }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Use an empty filter to find all documents

To find all documents, use an empty filter.

You should avoid this if you have a large number of documents.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var result = collection.Find();

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Include the similarity score with the result

If you use a vector search to find documents, you can also include a $similarity property for each document in the result. The $similarity value represents the closeness of the sort vector and the document’s vector.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

If you use a strongly typed object for your document, you must add a property to that object to handle receiving the similarity score:

[DocumentMapping(DocumentMappingField.Similarity)]
 public double Similarity { get; set; }
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var result = collection.Find(
      new CollectionFindOptions<Document>()
      {
        Sort = Builders<Document>.CollectionSort.Vectorize(
          "Text to vectorize"
        ),
        IncludeSimilarity = true,
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(
        JsonSerializer.Serialize(document["$similarity"])
      );
    }
  }
}

Include the sort vector with the result

If you use a vector search to find documents, you can also include the sort vector in the result. This can be useful if you do a vector search with $vectorize, since you don’t know the sort vector in advance.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static void Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var result = collection.Find(
      new CollectionFindOptions<Document>()
      {
        Sort = Builders<Document>.CollectionSort.Vectorize(
          "Text to vectorize"
        ),
        IncludeSortVector = true,
      }
    );

    // Inspect the sort vector
    Console.WriteLine(JsonSerializer.Serialize(result.GetSortVector()));
  }
}

Include only specific fields in the response

To specify which fields to include or exclude in the returned documents, use a projection.

All fields prefixed with $ are excluded by default and will only be returned if you include them in the projection. _id is included by default and will always be returned unless you exclude it from the projection.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.Eq("metadata.language", "English");

    var projection = Builders<Document>
      .Projection.Include("is_checked_out")
      .Include("title");

    var result = collection.Find(
      filter,
      new CollectionFindOptions<Document>() { Projection = projection }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Exclude specific fields from the response

To specify which fields to include or exclude in the returned document, use a projection.

All fields prefixed with $ are excluded by default and will only be returned if you include them in the projection. _id is included by default and will always be returned unless you exclude it from the projection.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.Eq("metadata.language", "English");

    var projection = Builders<Document>
      .Projection.Exclude("is_checked_out")
      .Exclude("title");

    var result = collection.Find(
      filter,
      new CollectionFindOptions<Document>() { Projection = projection }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Limit the number of documents returned

Specify a limit to only fetch up to a certain number of documents.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var result = collection.Find(
      new CollectionFindOptions<Document>() { Limit = 10 }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Skip documents

You can specify a number of documents to skip (bypass) before returning documents.

You can only do this if your find explicitly includes an ascending or descending sort criterion. You cannot do this in conjunction with vector search.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.Eq("metadata.language", "English");
    var result = collection.Find(
      filter,
      new CollectionFindOptions<Document>()
      {
        Sort = Builders<Document>
          .CollectionSort.Ascending("rating")
          .Descending("title"),
        Skip = 5,
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Use filter, sort, and projection together

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.And(
      filterBuilder.Eq("is_checked_out", false),
      filterBuilder.Lt("number_of_pages", 300)
    );

    var sort = Builders<Document>
      .CollectionSort.Ascending("rating")
      .Descending("title");

    var projection = Builders<Document>
      .Projection.Include("is_checked_out")
      .Include("title");

    var result = collection.Find(
      filter,
      new CollectionFindOptions<Document>()
      {
        Sort = sort,
        Projection = projection,
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Iterate over found documents

Use foreach to iterate over the found documents. The Data API returns results in pages. The CollectionFindCursor result handles the paging internally as part of the IEnumerable and IAsyncEnumerable implementations.

Alternatively, you can use the InitialPageState option to fetch a specific page of results. This is useful for cases where an external action triggers fetching the next page of results. For example, you might use this feature if you implement a "Load More" button or an infinite scroll interface.

If you need a list of all results, call ToList(). However, the time and memory required for this operation depend on the number of results. This is not recommended when you expect a large number of documents.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

Example using foreach:

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.And(
      filterBuilder.Eq("is_checked_out", false),
      filterBuilder.Lt("number_of_pages", 300)
    );
    var result = collection.Find(filter);

    // Use foreach
    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Example using InitialPageState:

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Create the filter
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.And(
      filterBuilder.Eq("is_checked_out", false),
      filterBuilder.Lt("number_of_pages", 300)
    );

    // Get the first page
    var cursor1 = collection.Find(filter);
    var page1 = await cursor1.FetchNextPageAsync();
    var results1 = page1.Results;
    foreach (var document in results1)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
    var paginationState1 = page1.NextPageState;

    // Get the next page
    if (paginationState1 != null)
    {
      var cursor2 = collection.Find(
        filter,
        new CollectionFindOptions<Document>()
        {
          InitialPageState = paginationState1,
        }
      );
      var page2 = await cursor2.FetchNextPageAsync();
      var results2 = page2.Results;
      foreach (var document in results2)
      {
        Console.WriteLine(JsonSerializer.Serialize(document));
      }
      var paginationState2 = page2.NextPageState;
    }
  }
}

Work with . and & in field names

You must use & to escape any . or & in field names when the field is used in a filter, sort, projection, update, or indexing clause. Dot notation, which is used to reference nested fields, should not be escaped. For more information, see Work with . and & in field names (C#).

For example, in the following document, you would use escaping like this: areas.r&&d, costs.price&.usd, and costs.price&.cad.

{
  "areas": {
    "r&d": true,
    "design": false
  },
  "costs": {
    "price.usd": 100,
    "price.cad": 90
  }
}
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.And(
      filterBuilder.Eq("areas.r&&d", false),
      filterBuilder.Lt("costs.price&.usd", 300)
    );

    var sort = Builders<Document>.CollectionSort.Ascending(
      "costs.price&.usd"
    );

    var projection = Builders<Document>
      .Projection.Include("areas.r&&d")
      .Include("costs.price&.cad");

    var result = collection.Find(
      filter,
      new CollectionFindOptions<Document>()
      {
        Sort = sort,
        Projection = projection,
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

You can also use the EscapeFieldNames function provided by the client:

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Utils;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.And(
      filterBuilder.Eq(
        FieldEscaping.EscapeFieldNames("areas", "r&d"),
        false
      ),
      filterBuilder.Lt(
        FieldEscaping.EscapeFieldNames("costs", "price.usd"),
        300
      )
    );

    var sort = Builders<Document>.CollectionSort.Ascending(
      FieldEscaping.EscapeFieldNames("costs", "price.usd")
    );

    var projection = Builders<Document>
      .Projection.Include(FieldEscaping.EscapeFieldNames("areas", "r&d"))
      .Include(FieldEscaping.EscapeFieldNames("costs", "price.cad"));

    var result = collection.Find(
      filter,
      new CollectionFindOptions<Document>()
      {
        Sort = sort,
        Projection = projection,
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Client reference

For more information, see the client reference.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM