I have JSON generated from excel via a vb-script. I import it to mongodb using mongoimport --jsonArray
It\'s creating a objectId on each document, but n
Is it possible with some option on monogoimport?
Nope.
is there anything I can write in my json to make it generate one on import?
Not to generate an ObjectId, but you can include an ObjectId in the JSON with the following notation:
{ "test" : { "$oid" : "5519e8ac996ef7f4636bfaec" } }
This would create a field called test
with value ObjectId("5519e8ac996ef7f4636bfaec")
. The value of the key $oid
needs to be a valid ObjectId.
do I have to use an API to do it?
Yes, that's what you'll need to generate the ObjectId values. You could either write a small script using, e.g., the Python driver to do the import and generate ObjectId's as part of it, or use mongoimport and then scan the collection and update each subdocument with an ObjectId:
> db.test.find()
{ "_id" : ObjectId("5519e8ac996ef7f4636bfaec"), "a" : [ { "x" : 1 }, { "y" : 2 } ] }
> db.test.find().forEach(function(doc) {
for (var i = 0; i < doc.a.length; i++) {
doc.a[i]._id = ObjectId()
}
db.test.update({ "_id" : doc._id }, doc)
} )
Note that, unless there's some specific reason to have an _id/ObjectId on a subdocument, like the _id
is a reference to another document, it's neither necessary nor desirable to put an ObjectId on every subdocument.