5

I am trying to load initial data to mongodb using db.collections.insert. I have a case where I'll insert the town collection followed by zipcode collection. The zipcode collection refers to town collection. However when I write my script, I do not know the _id of the town. Would like to know how to build the reference on the fly.

In the e.g. below, I need the id of Mancehster town to be populated in the place of "unkown".

db.town.insert({name:"Manchester",state:{$ref:"state", $id:"CT"},status:"NOT-SUBSCRIBED"});

db.zipcode.insert({_id:"06040", town:{$ref:"town", $id:"unkown"}});
db.zipcode.insert({_id:"06041", town:{$ref:"town", $id:"unkown"}});
db.zipcode.insert({_id:"06042", town:{$ref:"town", $id:"unkown"}});

If there is different way to load my initial data rather than db.collections.insert, I'd like to know that too.

Srik
  • 2,341
  • 2
  • 21
  • 35

1 Answers1

3

You can generate your own ObjectId's. Adjusting your example,

var town_id = ObjectId()
db.town.insert({ "_id" : town_id, "name" : "Manchester", "state" : { "$ref" : "state", "$id" : "CT" }, "status" : "NOT-SUBSCRIBED" })

db.zipcode.insert({ "_id" : "06040", "town" : { "$ref" : "town", "$id" : town_id } })
db.zipcode.insert({ "_id" : "06041", "town" : { "$ref" : "town", "$id" : town_id } })
db.zipcode.insert({ "_id" : "06042", "town" : { "$ref" : "town", "$id" : town_id } })

Alternatively, since you seem to be using custom values for _id for state and zipcode, you can make up your own unique _id instead of generating one.

Though I don't know much about your use case, I also have to comment that I think you are doing too much referencing. DBRefs are pretty much never necessary. In this case, you know that state will reference the state collection, so why put that in the state field? Just make the value of the state field be the _id of the state document. Better yet, don't reference at all and just put "state" : "CT". I doubt you really need a separate state collection. There's only 50 states and it's not like the names are going to change.

wdberkeley
  • 11,531
  • 1
  • 28
  • 23
  • You are right. I'll remove the DBref for state. I would like to retain the state collection though. It helps me to get the list of states quickly. – Srik Jan 15 '15 at 20:43