Ado Ren
Ado Ren

Reputation: 4394

How to insert into a collection dynamically?

I'd like to know if there is a way to insert into mongo db without going through the usual db.mycollection.insert but instead something like :

db.insert({collection: 'mycollection', document: ...})

Or even a more liberal approach to query such as : db.query(...)

Upvotes: 0

Views: 1058

Answers (1)

prasad_
prasad_

Reputation: 14287

You can define variables and use them in different ways to execute your queries (CRUD operations), in mongosh or the mongo shell.

Some examples:

var docs = [ { name: "John", city: "New York" }, { name: "Kim", city: "Oslo" } ]
var usersColl = "users"
var insertCmd = {
   insert: usersColl,
   documents: docs
}

Insert Documents (using any way suitable to you):

db.runCommand(insertCmd)
db.getCollection(usersColl).insertMany(docs);

Query:

db.getCollection(usersColl).find()

Assign collection to a variable and apply query methods on it:

var dbColl = db.getCollection(usersColl)
dbColl.insertOne({ name: "Jane", city: "Hamburg" })
dbColl.find()

References:

Upvotes: 1

Related Questions