0
votes

very easily put, I have two entitis like:

    public class SchoolClass
    {
        [JsonProperty(PropertyName = "id")]
        [Key]
        public Guid Id {get; init;} = Guid.NewGuid();

        // partition key
        public Guid SchoolClassCode {get; init;} = Guid.NewGuid();

        public int CountOfComputer {get; set;}
    }

and

    public class Computer
    {
        [JsonProperty(PropertyName = "id")]
        [Key]
        public Guid Id {get; init;} = Guid.NewGuid();

        // class where the computer is located (link to SchoolClass class - SchoolClassCode prop)
        public Guid SchoolClass {get; set;}
    }

I would like to write stored procedure, that would increase the count of computers in school class, once some computer is added to the db.

I have following problem: I do not know, how to search in the collection using partition key. I need something very similar to this example https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-model-partition-example#denormalizing-comment-and-like-counts. But they use id for searching in the collection and I would like to use partition key of SchoolClass class (SchoolClassCode property), which I have in Computer class (SchoolClass property). I do not have id of SchoolClass class in Computer class and due to that I am not able to find the specific SchoolClass to be able to increase the counter.

So what I need is something like this:

function createComment(computer) {
  var collection = getContext().getCollection();

  collection.readDocument(
    `${collection.getAltLink()}/docs/${computer.SchoolClass}`,
    function (err, schoolClass) {
      if (err) throw err;

      schoolClass.CountOfComputer++;
      collection.replaceDocument(
        schoolClass._self,
        schoolClass,
        function (err) {
          if (err) throw err;
        }
      );
    })
}

But collection.getAltLink()}/docs/ works only with entity id and not partition key. How I can search in the collection using partition key so it is performance effective? Thanks!

1

1 Answers

1
votes

You can use queryDocuments function like this:

function createComment(computer) {
  var collection = getContext().getCollection();

  collection.queryDocuments(
    collection.getSelfLink(),
    'SELECT * FROM root r where r.SchoolClassCode = ' + computer.SchoolClass,
    function (err, items) {
      if (err) throw err;

      if(items && items.length){
        var schoolClass = items[0];
        schoolClass.CountOfComputer++;
        collection.replaceDocument(
            schoolClass._self,
            schoolClass,
            function (err) {
            if (err) throw err;
            }
        );
      }
    })
}