3

Let's say we have a container with following items

{
  location:CA,
  bool: false
}

{
  location:CA,
  bool: false
}

{
  location:CA,
  bool: false
}

How do we write a stored procedure to query all items and update all item's bool field from false to true? I have not find any reference yet and I know CosmosDB stored procedure only support querying not updating or deleting.

szastronaut
  • 55
  • 1
  • 5

1 Answers1

2

This stored procedure code:

// SAMPLE STORED PROCEDURE
function sample() {
    var collection = getContext().getCollection();

    // Query all documents in one logic partition
    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT * FROM root r',
    function (err, feed, options) {
        if (err) throw err;

        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            response.setBody('no docs found');
        }
        else {
            feed.forEach(element => {
                element.bool = true;
                collection.replaceDocument(element._self, element,function (err){
                    if (err) throw err;
                })
            })
            var response = getContext().getResponse();
            response.setBody("replace success");
        }
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

Execute stored procedure: enter image description here

BTW, your partition key should be /location.

Steve Johnson
  • 8,057
  • 1
  • 6
  • 17