简体   繁体   中英

Update a property value in my Documentdb

I have the following result in my document. I wanted to update the property value for "Type" and "Workout", such that it doesn't effect other values

"PartyId": 10114795,
"WorkoutId": 4,
"Type": "heart-rate-zone-target",
"DateStarted": "2016-02-05T18:14:15.1620890Z",
"id": "0c44d1ee-58b8-4083-a702-f770ba0e63e9",
"_rid": "0ThoANQ4YwEEAAAAAAAAAA==",
"_self": "dbs/0ThoAA==/colls/0ThoANQ4YwE=/docs/0ThoANQ4YwEEAAAAAAAAAA==/",
"_etag": "\"08000130-0000-0000-0000-58dd72da0000\"",
"_attachments": "attachments/",
"_ts": 1490907866

I wanted to update the property value for "Type" and "Workout", such that it doesn't effect other values.

I did a demo for just updating the specified property. The following is my detail steps:

1.Create a C# console project and reference Azure DocumentDB SDK

2.Add a TestModel class

 public class TestModel
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        // used to set expiration policy
        [JsonProperty(PropertyName = "ttl", NullValueHandling = NullValueHandling.Ignore)]
        public int? TimeToLive { get; set; }
        public string PartyId { get; set; }
        public string Type { get; set; }
        public DateTime DateStarted { get; set; }
        public int WorkoutId { get; set; }

    }

3. Add the document to collection

 private static readonly string databaseName = "tomtest";
 private static readonly string collectionName = "colltest";
  // Read config
 private static readonly string endpointUrl = ConfigurationManager.AppSettings["EndPointUrl"];
 private static readonly string authorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];

        var client = new DocumentClient(new Uri(endpointUrl),authorizationKey);
        Console.WriteLine();
        Console.WriteLine("**** Create Documents ****");
        Console.WriteLine();
        var document1Definition = new TestModel
        { 
            Id= Guid.NewGuid().ToString(),
            PartyId = "10114795",
            Type = "heart-rate-zone-target",
            DateStarted = DateTime.Now,
            WorkoutId = 4
        };

        var database = client.CreateDatabaseIfNotExistsAsync(new Database {Id = databaseName}).Result.Resource;
        var collection = client.CreateDocumentCollectionIfNotExistsAsync(
            UriFactory.CreateDatabaseUri(databaseName), new DocumentCollection
            {
               Id = collectionName
            }).Result.Resource;
        //create document
        var createdocument = client.CreateDocumentAsync(collection.SelfLink, document1Definition).Result.Resource; 

4.Check the result from the Azure portal

在此处输入图片说明

5.Query the created document

 //query document
 var querydoc = client.CreateDocumentQuery<TestModel>(
 UriFactory.CreateDocumentCollectionUri(databaseName, collectionName))
            .Where(x => x.PartyId == "10114795")
            .AsEnumerable()
            .First();

6.Update the document.

//update document
querydoc.Type = "updateType";
querydoc.WorkoutId = 0;
var result = client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, querydoc.Id), querydoc).Result.Resource;
            Console.WriteLine(result);
            Console.WriteLine($"Update document Type :{ result.GetPropertyValue<string>("Type")} , WorkoutId:{result.GetPropertyValue<int>("WorkoutId")}");

7.Check from Azure portal and console.

在此处输入图片说明

在此处输入图片说明

Packages.config

<packages>
  <package id="Microsoft.Azure.DocumentDB" version="1.13.1" targetFramework="net451" />
  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net451" />
</packages>

Unfortunately, partial update is not yet implemented. You can track the process at https://feedback.azure.com/forums/263030-azure-cosmos-db/suggestions/6693091-be-able-to-do-partial-updates-on-document

So, as Tom Sun mentioned you can first retrieve the required document from Cosmos DB, update the properties and replace with the older one.

//Fetch the Document to be updated
Document doc = client.CreateDocumentQuery<Document>(collectionLink)
                            .Where(r => r.Id == "doc id")    
                            .AsEnumerable()
                            .SingleOrDefault();

//Update some properties on the found resource
doc.SetPropertyValue("MyProperty", "updated value");

//Now persist these changes to the database by replacing the original resource
Document updated = await client.ReplaceDocumentAsync(doc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM