2

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:

  • cloneCollection - didn't work. is for cloning across databases.

  • aggregate with an $out operator - that copies just the data but not the indexes.

The aggregate command I've tried:

{"aggregate":"orig_coll", "pipeline":[{"$out":"orig_clone"}]}
rustyx
  • 80,671
  • 25
  • 200
  • 267
  • Looks like this has what you're looking for: http://stackoverflow.com/questions/10624964/whats-the-fastest-way-to-copy-a-collection-within-the-same-database – dyouberg Aug 25 '16 at 15:09
  • Yes but I specifically need a JSON command, and I need to copy indexes too. I can't use the proposed solution with `mongoexport`/`mongoimport`. – rustyx Aug 25 '16 at 15:20

1 Answers1

1

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 ...

rustyx
  • 80,671
  • 25
  • 200
  • 267
loicmathieu
  • 5,181
  • 26
  • 31
  • I can certainly pass commands via the JSON interface. It's just there is no [command](https://docs.mongodb.com/manual/reference/command/nav-administration/#administration-commands) to clone a collection. – rustyx Jul 26 '21 at 11:21