I’ve recently learned about the RETURNING keyword in N1QL. When you add it to end of a N1QL query, that query will return the result set that was operated on. For instance, if you use an UPDATE, and that query updates 10 documents, the RETURNING will then return those 10 documents.

You can use this within your .NET and .NET Core Couchbase applications.

Basic Setup

This blog post assumes that you have Couchbase Server setup locally, a bucket created called “default”, and at least a primary index created on that bucket.

Note: if you are having trouble getting started with Couchbase Server, or you are getting errors, especially in regards to N1QL indexing, you may want to revisit some of my “Getting Started” blog posts: Couchbase with Windows Part 1 and Couchbase with Windows Part 2 in particular.

I’m using a simple .NET Core console project, with the same tooling and setup that I used in my .NET Core with Visual Studio Code blog post.

Coding with .NET and N1QL

Most of this code should be pretty familiar if you’ve used .NET and Couchbase before. I’m creating 5 documents that have (initially) a processed field set to false. The code below inserts them. It also writes them out to console for illustration purposes.

Next, this code immediately runs a N1QL UPDATE to set all the processed fields to true. It also has a RETURNING statement at the end to return the documents as well as the keys.

Finally, the following code prints out the returned JSON to console for illustration purposes.

Running the program

To execute this program, simple enter dotnet run at the console window. You should see an output like this:

Console output demonstrating the N1QL RETURNING keyword

Summary

The RETURNING keyword can save you a step when updating/inserting a group of documents. Try experimenting with a more complex UPDATE to see what happens. For example, try using IS MISSING instead of relying on a boolean flag like 'processed'.

If you have any questions, please leave a comment or contact me on Twitter.

Posted by Matthew Groves, Developer Advocate

Matthew is a Developer Advocate for Couchbase, and lives in the Central Ohio area. He has experience as a web developer as a consultant, in-house developer, and product developer. He has been a regular speaker at conferences and user groups all over the United States, and he has written AOP in .NET for Manning Books. He has experience in C# and .NET, but also with other web-related tools and technologies like JavaScript and PHP. You can find him on Twitter at @mgroves.

Leave a reply