Create _id on subdocuments on mongoimport --jsonArray

后端 未结 1 1119
暖寄归人
暖寄归人 2021-01-07 15:37

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

相关标签:
1条回答
  • 2021-01-07 16:14

    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.

    0 讨论(0)
提交回复
热议问题