cosmos db

How to handle a array of Json object in Cosmos db using C

Working with Arrays of JSON Objects in Cosmos DB using C#.NET

Cosmos DB, Microsoft’s fully managed NoSQL database service, offers remarkable flexibility in handling data, including arrays of JSON objects. This article will guide you through practical techniques for effectively managing and querying such arrays in your C# applications.

1. Defining Your Data Model

Before diving into code, let’s consider a basic example. Imagine a database storing information about users, each having an array of “favorites” representing their preferred items:

{
  "id": "user1",
  "name": "John Doe",
  "favorites": [
    { "type": "book", "title": "The Hitchhiker's Guide to the Galaxy" },
    { "type": "movie", "title": "The Matrix" }
  ]
}

In your C# code, you’ll represent this data structure using classes:

public class User
{
    public string id { get; set; }
    public string name { get; set; }
    public List<Favorite> favorites { get; set; }
}

public class Favorite
{
    public string type { get; set; }
    public string title { get; set; }
}

2. Accessing Cosmos DB with the SDK

To interact with Cosmos DB, you’ll utilize the Azure Cosmos DB .NET SDK. Install the necessary NuGet package:

Install-Package Microsoft.Azure.Cosmos

Then, establish a connection to your Cosmos DB account:

// Replace with your Cosmos DB connection string
string connectionString = "YOUR_CONNECTION_STRING";
// Replace with your database and container names
string databaseId = "yourDatabase";
string containerId = "yourContainer";

CosmosClient client = new CosmosClient(connectionString);
Database database = client.GetDatabase(databaseId);
Container container = database.GetContainer(containerId);

3. Working with Array Data

3.1 Inserting Data

To insert a document containing an array of objects, simply create an instance of your User class and add it to the container:

User newUser = new User
{
    id = "user2",
    name = "Jane Smith",
    favorites = new List<Favorite>()
    {
        new Favorite { type = "music", title = "Bohemian Rhapsody" },
        new Favorite { type = "food", title = "Sushi" }
    }
};

await container.CreateItemAsync<User>(newUser);

3.2 Querying Data

Cosmos DB provides powerful query capabilities for interacting with array data. Let’s demonstrate retrieving users who have a specific favorite item:

// Query for users who have a favorite movie with title "The Matrix"
var query = new QueryDefinition("SELECT * FROM c WHERE ARRAY_CONTAINS(c.favorites, { type: 'movie', title: 'The Matrix' })");

FeedIterator<User> iterator = container.GetItemQueryIterator<User>(query);

while (iterator.HasMoreResults)
{
    FeedResponse<User> response = await iterator.ReadNextAsync();

    foreach (User user in response)
    {
        Console.WriteLine($"User: {user.name} - ID: {user.id}");
        // Access individual favorites using user.favorites
    }
}

3.3 Updating Array Data

Modifying elements within the array requires careful consideration. You can either:

a. Replace the entire array:

// Retrieve user with id "user1"
User user = await container.ReadItemAsync<User>("user1", new PartitionKey("user1"));

// Modify the favorites array
user.favorites.Add(new Favorite { type = "game", title = "Super Mario Odyssey" });

// Replace the entire document
await container.ReplaceItemAsync<User>(user, "user1", new PartitionKey("user1"));

b. Use the PATCH method:

// Retrieve user with id "user1"
User user = await container.ReadItemAsync<User>("user1", new PartitionKey("user1"));

// Add a new favorite
var patch = new PatchOperation[]
{
    PatchOperation.Add("/favorites", new Favorite { type = "game", title = "Super Mario Odyssey" })
};

// Apply the patch
await container.PatchItemAsync<User>("user1", new PartitionKey("user1"), patch);

3.4 Deleting Array Data

You can remove items from the array by using the PATCH method with the Remove operation:

// Retrieve user with id "user1"
User user = await container.ReadItemAsync<User>("user1", new PartitionKey("user1"));

// Remove a specific favorite
var patch = new PatchOperation[]
{
    PatchOperation.Remove("/favorites[0]") // Remove the first element in the array
};

// Apply the patch
await container.PatchItemAsync<User>("user1", new PartitionKey("user1"), patch);

Conclusion

Cosmos DB empowers developers to handle arrays of JSON objects seamlessly within their C# applications. By understanding the concepts outlined in this article, you can confidently store, query, update, and delete data in your Cosmos DB containers, leveraging the full potential of its flexible data model. Remember to explore the Cosmos DB .NET SDK documentation for further details and advanced capabilities.

Scroll to Top