Question

Question: How do I insert an array of simple strings as new documents with a single call? I don't want to convert it before. I am looking for some mongo magic here. The $push, $each things don't seem to work for insertions.

var newTags = [];
newTags.push("tagA");
newTags.push("tagB");

// with this lodash conversion the batch insertion works fine.
// ["tagA", "tagB"] -> [{name: "tagA", name: "tagB"}]
// newTags = _.map(newTags, function(key) {return {'name': key}});

db.collection('tags').insert(newTags, {w: 1},  function (err, result) {

});

My definition of 'not working'

Mongo does insert the newTags, but creates a document from each string like this.
I understand why it does it

{
  "_id": "111111116c021a165abcdd16",
  "0": "t",
  "1": "a",
  "2": "g",
  "3": "A"
},
{
  "_id": "111111126c021a165abcdd17",
  "0": "t",
  "1": "a",
  "2": "g",
  "3": "B"
}

but should be

{ 
  "_id": "111111116c021a165abcdd16",
  "name": "tagA"
},
{ 
  "_id": "111111126c021a165abcdd17",
  "name": "tagB"
}
Was it helpful?

Solution

To my knowledge it's not possible, because for inserting, MongoDB either accepts a single document object, or an array of such objects, but not an array of scalars.

Which IMO makes sense, because how would MongoDB know that you want to map those scalars to a particular field (name, in this case)? That's application logic, not database logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top