how to create mongoDB objectid in java

AmeyChavan picture AmeyChavan · Jun 12, 2014 · Viewed 17.1k times · Source

Refering to post How to add an array to a MongoDB document using Java? I have created a mongo schema using java it has sub elements, I am getting _id for main document I would like to get _id in sub elements also here output looks (I have marked the portion where I need _id) b.party.find().pretty();

{

"_id" : ObjectId("5399aba6e4b0ae375bfdca88"),
"addressDetails" : [
    {
        //   _id here
        "locationName" : "Office",
        "phones" : [
            {   //   _id here   
                "name" : "Tel1",
                "value" : "95253-"
            },
            {   //   _id here
                "name" : "Tel2",
                "value" : "95253-"
            },
            {   //   _id here
                "name" : "Tel3",
                "value" : "95253-"
            },
            {   //   _id here
                "name" : "Fax1",
                "value" : "0253-"
            }
        ],
        "address" : "A-3,MIDCA-3,MIDC",
        "defaultBillAddrerss" : "",
        "pincode" : "422 010",
        "city" : null,
        "state" : "1",
        "country" : ""
    },
    {       //   _id here
        "locationName" : "Factory",
        "phones" : [
            {   //   _id here
                "name" : "Tel1",
                "value" : "0253-"
            },
            {   //   _id here
                "name" : "Tel2",
                "value" : "0253-"
            },
            {   //   _id here
                "name" : "Tel3",
                "value" : "0253-"
            },
            {   //   _id here
                "name" : "Fax1",
                "value" : "0253-"
            }
        ],
        "address" : "A-3 INDUSTRIAL AREA,",
        "defaultBillAddrerss" : "",
        "pincode" : "422 010",
        "city" : null,
        "state" : "1",
        "country" : ""
    }
],
"crLimit" : "0.0",
"crPeriod" : "",
"name" : "CROMPTON GREAVES  "

}

Java code to create is similar to How to add an array to a MongoDB document using Java?

Is there any code to create ObjectId("") programmatically in java?

Answer

mohamedrias picture mohamedrias · Jun 12, 2014

To create objectId programmatically, use the following syntax

import org.bson.types.ObjectId;


ObjectId id1 = new ObjectId();
ObjectId id2 = ObjectId.get();

// In case you want to mention the parent ID itself,
ObjectId id3 = new ObjectId("5399aba6e4b0ae375bfdca88");