Over a million developers have joined DZone.

Copying Documents Between Buckets in Couchbase

Want to copy your data from one Couchbase bucket to another? It just takes a bit of N1QL.

· Database Zone

Build fast, scale big with MongoDB Atlas, a hosted service for the leading NoSQL database. Try it now! Brought to you in partnership with MongoDB.

When I’m at a user group or conference, people often come up to me afterwards with good questions. This is a great way for me to get blog post ideas: if they have a question, chances are lots of other people have the same one. It’s also a great way for me to get to know Couchbase better.

This post is for one of those questions: Can I copy documents from one bucket to another?

Yes! In fact, if you’ve done this sort of thing in SQL, then you are not too far from already knowing the answer.

Fire buckets Image Licensed through Creative Commons via Paul Harrop - http://www.geograph.org.uk/photo/2666296

There are command line tools to backup/restore a bucket, but for this post, I’m going to assume that what you want is to make a copy of some documents from bucket A into bucket B.

It’s as easy as using a N1QL INSERT.

Start by creating a N1QL SELECT to get the documents you want out of the first bucket. I’m going to show a very simplified SELECT that gets all the documents from my default bucket. If you only want a subset, you can use a WHERE clause.

SELECT META().id _k, _v
from `default` _v

Since we’re copying to another bucket, we need both the key and the document itself. This query selects the document key using the META() function and selects the document using a _v alias.

Next, I’ll create an INSERT to put these selected documents into another bucket, which I called target.

INSERT INTO `target` (KEY _k, VALUE _v)
SELECT META().id _k, _v
from `default` _v

An INSERT needs a key and a value. I have those from the SELECT. All done.

Now it's easier than ever to get started with MongoDB, the database that allows startups and enterprises alike to rapidly build planet-scale apps. Introducing MongoDB Atlas, the official hosted service for the database on AWS. Try it now! Brought to you in partnership with MongoDB.

couchbase,user group,user,bucket

Published at DZone with permission of Matthew Groves. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}