Reputation: 109
I want to initialise a mongoDB with a script because I have some collection that I need to have values in the beginning So i followed the instructions: http://michelebusta.com/the-little-things-5-initialize-a-local-mongo-db/
I create a (.js) file I load it and it works,
db.serviceSpeedList.insert({
_id: 0,
name:"DHL", service:"DHL Ground"});
db.serviceSpeedList.insert({
_id: 1,
name:"DHL", service:"DHL Second Day Service"});
db.serviceSpeedList.insert({
_id: 2,
name:"DHL", service:"DHL Express"});
db.serviceSpeedList.insert({
_id: 3,
name:"DHL", service:"DHL International Express"});
the problem is that I have ID like this: "_id" : ObjectId("572b8601e6352994d76bb13e"), and I want to have an auto-increment Id (_id: 1), can you please Help me.
{
"_id" : ObjectId("572b8601e6352994d76bb139"),
"name" : "DHL",
"service" : "DHL Ground"
}
{
"_id" : ObjectId("572b8601e6352994d76bb13a"),
"name" : "DHL",
"service" : "DHL Second Day Service"
}
I used
var i= 0;
db.serviceSpeedList.insert({ "_id" : i++, name:"DHL", service:"DHL Ground"});
WriteResult({ "nInserted" : 1 })
db.serviceSpeedList.insert({"_id" : i++, name:"DHL", service:"DHL Second Day Service"});
WriteResult({ "nInserted" : 1 })
When I use it in the shell separately it works but when i put it in a script and use load ("D:\initMongo.js"); it doesn't work :( please help me
Upvotes: 1
Views: 925
Reputation: 2316
you will have to perform an auto increment sequence in your mongodb database to do so. Complete exemple can be found : https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
Upvotes: 1
Reputation: 19533
You can set _id as any other property, if you have a js file, consider use a var i = 0;
and increment that in each insert statement.
db.serviceSpeedList.insert({ "_id" : i++, name:"DHL", service:"DHL Ground"});
db.serviceSpeedList.insert({"_id" : i++, name:"DHL", service:"DHL Second Day Service"});
Just follow the flow
> var i = 0;
> db.serviceSpeedList.insert({ "_id" : i++, name:"DHL", service:"DHL Ground"});
WriteResult({ "nInserted" : 1 })
> db.serviceSpeedList.findOne()
{ "_id" : 0, "name" : "DHL", "service" : "DHL Ground" }
> db.serviceSpeedList.insert({"_id" : i++, name:"DHL", service:"DHL Second Day S
ervice"});
WriteResult({ "nInserted" : 1 })
> db.serviceSpeedList.find()
{ "_id" : 0, "name" : "DHL", "service" : "DHL Ground" }
{ "_id" : 1, "name" : "DHL", "service" : "DHL Second Day Service" }
>
Upvotes: 1