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.
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
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
Next, I’ll create an
INSERT to put these selected documents into another bucket, which I called
INSERT INTO `target` (KEY _k, VALUE _v) SELECT META().id _k, _v from `default` _v
INSERT needs a key and a value. I have those from the
SELECT. All done.