Home > other >  How to insert into a collection dynamically?
How to insert into a collection dynamically?

Time:09-16

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

CodePudding user response:

You can define variables and use them in different ways to excute your qureies (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:

  • Related