Insert _id as number


#1

I want add _id as a number in mongodb collection from my meteor application can it is possible?if yes than how?

Thanks in advance

for example "_id" : 2204


#2

The best you can do is cast the number to a string:

"_id": String(someNumber)

#3

if i want to only number not string than possible


#4

Generally the best solution is to put it in a separate field and just keep the original ID as well.


#5

yes @lucfranken i know but at the start of my application i added collection data from node js listner like this
"_id" : 2204, "assets_name" : "testing", "created_at" : ISODate("2015-01-19T22:48:44.000Z"), "created_by" : "ntgfMjrBE7hde2zpj"

and my 90% application complete and now i want also add some data from meteor side


#6

Maybe just rename the _id field to _new_id_field and generate new correct id’s which Meteor can handle?


#7

I suggest doing a data migration. In your mongo shelll:

db.yourCollectionName.find().forEach(function (doc) {
  db.yourCollectionName.update({_id: doc._id}, {$set: {numberId: doc._id}});
});

Then you can proceed as lucfranken suggested above.


#8

thats good idea @lucfranken

but why i dont insert _id as number?


#9

Because Meteor by default uses another type of ID which might create issues down the run. Generally I prefer to keep custom things like numbered ID’s outside of Meteor so it prevents any issues at all.

If needed you can add an index on it for performance:
https://docs.mongodb.org/v3.0/reference/method/db.collection.ensureIndex/


#10

Thank You So Much To All Of You