Reputation: 155
I want to insert a variable, say,
a = {1:2,3:4}
into my database with a particular id "56". It is very clear from the docs that I can do the following:
db.testcol.insert({"_id": "56", 1:2, 3:4})
However, I cannot figure out any way to insert "a" itself, specifying an id. In other words, I want to do something like this
db.testcol.insert(a, "_id"="56")
but it does not work. Is it possible at all?
Upvotes: 3
Views: 3912
Reputation: 4285
Insert only accepts a final document or an array of documents, and an optional object which contains additional options for the collection.
db.collection.insert(
<document or array of documents>,
{ // options
writeConcern: <document>,
ordered: <boolean>
}
)
You may want to add the _id to the document in advance, but separated from document's creation:
a = {1:2,3:4}
Using dot notation:
a._id = 56;
Using square bracket notation:
a['_id'] = 56;
Then, the insert:
db.testcol.insert(a);
Result:
{
"_id" : 56,
"1" : 2,
"3" : 4
}
By the way, this is actually how you would add a key-value pair to an object in JavaScript.
Upvotes: 2