How to copy a collection from one database to another in MongoDB

前端 未结 19 1507
無奈伤痛
無奈伤痛 2020-11-28 00:22

Is there a simple way to do this?

相关标签:
19条回答
  • 2020-11-28 01:09

    In case some heroku users stumble here and like me want to copy some data from staging database to the production database or vice versa here's how you do it very conveniently (N.B. I hope there's no typos in there, can't check it atm., I'll try confirm the validity of the code asap):

    to_app="The name of the app you want to migrate data to"
    from_app="The name of the app you want to migrate data from"
    collection="the collection you want to copy"
    mongohq_url=`heroku config:get --app "$to_app" MONGOHQ_URL`
    parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
    to_token=${parts[0]}; to_url=${parts[1]}; to_db=${parts[2]}
    mongohq_url=`heroku config:get --app "$from_app" MONGOHQ_URL`
    parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
    from_token=${parts[0]}; from_url=${parts[1]}; from_db=${parts[2]}
    mongodump -h "$from_url" -u heroku -d "$from_db" -p"$from_token" -c "$collection" -o col_dump
    mongorestore -h "$prod_url" -u heroku -d "$to_app" -p"$to_token" --dir col_dump/"$col_dump"/$collection".bson -c "$collection"
    
    0 讨论(0)
提交回复
热议问题