rustyx
rustyx

Reputation: 85316

mongodb duplicate a collection within the same database

I want to clone an existing collection, including data and indexes, to a new collection with another name within the same database, using mongodb JSON interface (not the command-line interface).

I've tried:

The aggregate command I've tried:

{"aggregate":"orig_coll", "pipeline":[{"$out":"orig_clone"}]}

Upvotes: 2

Views: 1638

Answers (1)

loicmathieu
loicmathieu

Reputation: 5562

There is no way to do this in one JSON query.

So, two solutions here :

  1. Using mongodump/mongorestore as proposed in What's the fastest way to copy a collection within the same database?
  2. Using two queries : one to create the destination table with the index and the aggregate query that you already have. I understand that it's not a perfect solution as you need to maintain the query to create the index on the destination table and the index on the source table but there's no other way to do this.

What you need to understand is that, the JSON interface as you told it is not a database interface but a database JavaScript query language. So you can pass query to it not command. In fact, it's not an interface just a query DSL. The interface is the mongo shell or any of the mongo drivers (java, perl, ...) or any of the mongo admin tools ...

Upvotes: 1

Related Questions