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.

Author

Posted by Matthew Groves

Matthew D. Groves is a guy who loves to code. It doesn't matter if it's C#, jQuery, or PHP: he'll submit pull requests for anything. He has been coding professionally ever since he wrote a QuickBASIC point-of-sale app for his parent's pizza shop back in the 90s. He currently works as a Senior Product Marketing Manager for Couchbase. His free time is spent with his family, watching the Reds, and getting involved in the developer community. He is the author of AOP in .NET, Pro Microservices in .NET, a Pluralsight author, and a Microsoft MVP.

Leave a reply