0

Given the following array:

arr = ["{'myId': 'myVal1'}","{'myId': 'myVal2'}"]

I can insert the items one by one, e.g.

db.collection.insert(arr[0])

But it fails when I try to insert the whole array (like it says in http://docs.mongodb.org/manual/reference/method/db.collection.insert/ )

db.collection.insert(arr)
Error: not an object src/mongo/shell/collection.js:179

I'm using MongoDB 2.2.4

How can I make this work?

Manuel
  • 10,869
  • 14
  • 55
  • 86

1 Answers1

1

You are trying to insert an array of strings - mongo expects an array of json documents.

"{'foo':'bar'}" is a string.
{'foo':'bar'} is an object - a json document with one key value pair.

It looks to you like the insert is succeeding when you do

db.collection.insert("{'foo':'bar'}") but it's not doing what you think it is.

> db.collection.findOne()
{
    "_id" : ObjectId("51941c94c12b0a7bbd416430"),
    "0" : "{",
    "1" : "'",
    "2" : "f",
    "3" : "o",
    "4" : "o",
    "5" : "'",
    "6" : ":",
    "7" : "'",
    "8" : "b",
    "9" : "a",
    "10" : "r",
    "11" : "'",
    "12" : "}",
    "trim" : function __cf__12__f__anonymous_function() {
    return this.replace(/^\s+|\s+$/g, "");
},
    "ltrim" : function __cf__13__f__anonymous_function() {
    return this.replace(/^\s+/, "");
},
    "rtrim" : function __cf__14__f__anonymous_function() {
    return this.replace(/\s+$/, "");
},
    "startsWith" : function __cf__15__f__anonymous_function(str) {
    return this.indexOf(str) == 0;
},
    "endsWith" : function __cf__16__f__anonymous_function(str) {
    return (new RegExp(RegExp.escape(str) + "$")).test(this);
}
}

I already put a pointer to this question/answer in your other question which asks how to convert this string.

Community
  • 1
  • 1
Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133