Insert multiple documents with same default fields

Hi there, I have a question on insert operation.

My goal is to insert multiple documents. All of these documents are sharing the same default value for all fields except id. For example:

{"id": "name0", "team": "engineer", "manager": "boss1", ....}
{"id": "name1", "team": "engineer", "manager": "boss1", ....}
{"id": "name2", "team": "engineer", "manager": "boss1", ....}

Is there an operation that can help me achieve this insertion by not duplicate all default value multiple times? I can think of an approach with two steps, 1. inject id field only 2. update field to default value by filtering on “id” field. But is there a way to achieve this in single step?

I find $setOnInsert function on update operation interesting, because

db.testInsertion.update({"id": "name0"}, {"$setOnInsert": {"team": "engineer", "manager": "boss1"}}, {"upsert":true}) is adding "id" field even when it is not mentioned in $setOnInsert. But following does not work: 
db.testInsertion.update({"id": {"$in": ["name0", "name1", "name2"]}, {"$setOnInsert": {"team": "engineer", "manager": "boss1"}}, {"upsert":true}, {"$multiple": true}) 

Am I on the right direction?

Hi @Sunan_Jiang! Welcome to the community!

I’m not exactly sure what you’re trying to accomplish, so my apologies if you’ve already considered the following:

MongoDB will automatically create an _id field for you if you do not specify it. If you want a meaningful _id (perhaps you want to take advantage of the default index on _id so you want _id to be something unique like an employee id), you should set it. If you don’t care with the _id is, you don’t have to set it.

My instinct based on what you have written would be to write a script in my favorite programming language to generate the documents to be inserted and then use insertMany() to insert them. This would allow you to programmatically set the default values.

Is there a reason you’re only searching for those 3 documents in your second example? It’s unclear to me if you’re trying to set a permanent default or you’re trying to set defaults for an initial set of documents.

1 Like

Hello @Sunan_Jiang, here is an approach you can try. This is from the mongo shell:

var insert_array = [ ]
var ids_to_insert = [ "name0", "name1", ""name2" ]

for (let id of ids_to_insert) {
    let doc = { "team": "engineer", "manager": "boss1"  }    // shared default fields/values
    doc["_id"] = id
    insert_array.push(doc)
}

db.test.insertMany(insert_array)
3 Likes