Create _id in mongoimport subdocuments --jsonArray

I have JSON generated from excel via vb-script. I import it into mongodb using mongoimport --jsonArray

It creates an object for each document, but not for subdocuments. What is the best way to create them? Is it possible with some options on monogoimport? Or do I need to use the API for this? Or is there anything I can write in my json so that it will generate it upon import?

0
mongodb
source share
1 answer

Is it possible using any option in monogoimport?

Nope.

is there anything i can write in my json so that it will generate it upon import?

Do not create an ObjectId, but you can include ObjectId in JSON with the following notation:

 { "test" : { "$oid" : "5519e8ac996ef7f4636bfaec" } } 

This will create a field called test with a value of ObjectId("5519e8ac996ef7f4636bfaec") . The key value $oid must be a valid ObjectId.

Do I need to use the API for this?

Yes, this is what you need to create ObjectId values. You can either write a small script using, for example, the Python driver to import, and generate an ObjectId as part of it, or use mongoimport, and then scan the collection and update each sub-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) } ) 

Please note that if there is no specific reason for the presence of _id / ObjectId in the subdocument, for example, _id is a link to another document, it is not necessary and not advisable to put an ObjectId for each attached document.

+5
source share

All Articles