Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a variable in MongoDB specifying _id field

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?

like image 789
Alekz112 Avatar asked Jul 22 '26 08:07

Alekz112


1 Answers

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.

like image 156
TechWisdom Avatar answered Jul 24 '26 22:07

TechWisdom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!