Atlante Avila
Atlante Avila

Reputation: 1488

Adding a new collection to an existing mongo database

I have an existing db with a bunch of collections in it. I need to add a new collection and was asked to create a script to add this collection in our production environment. Not sure how to approach this. When I search for this, I see docs pointing to insert() in mongodb, but that looks like a way to insert new documents in to an existing collection.

Is there a way to add a script to the load() function to be able to create a new collection inside my db?

Thanks!

Upvotes: 0

Views: 1156

Answers (2)

Taylor Ackley
Taylor Ackley

Reputation: 1437

When you do an insert with collection xyz specified, the collection xyz will create itself if it does not exist yet.

You can do createCollection if you need specific options, but this is rare.

https://docs.mongodb.com/manual/reference/method/db.createCollection/

Upvotes: 1

Natu Myers
Natu Myers

Reputation: 496

You could either use the mongo command line tool or use js files to do this.

By "script", I'm assuming make a js file.

In either the CLI or in a js file:

use video;
db.movies.insertOne({ "title": "Jaws", "year": 1975, "imdb": "tt0073195" });
db.movies.insertOne({ "title": "Mad Max 2: The Road Warrior", "year": 1981, "imdb": "tt0082694" })
db.movies.insertOne({ "title": "Raiders of the Lost Ark", "year": 1981, "imdb": "tt0082971" })

Will insert those objects into a collection called video in a database called movies.

I suggest reading up on the mongo docs on how to use the CLI or pass js files to your instance because there are countless answers here on SO. https://docs.mongodb.com/manual/reference/command/ https://docs.mongodb.com/manual/reference/method/db.createCollection/

From https://docs.mongodb.com/manual/reference/program/mongo/ and https://docs.mongodb.com/manual/reference/mongo-shell/ The mongo shell can be started with numerous options. See mongo shell page for details on all available options (https://docs.mongodb.com/manual/reference/program/mongo/) then run your commands.

Upvotes: 1

Related Questions