如何在java中创建mongoDB objectid

时间:2014-06-12 13:54:02

标签: java mongodb mongodb-java

参阅帖子How to add an array to a MongoDB document using Java? 我用java创建了一个mongo模式 它有子元素,我得到主文件_id 我想在子元素中获得_id输出外观(我已经标记了我需要的部分_idb.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代码类似于How to add an array to a MongoDB document using Java?

是否有任何代码可以在java中以编程方式创建ObjectId("")

2 个答案:

答案 0 :(得分:14)

要以编程方式创建objectId,请使用以下语法

ObjectId id = new ObjectId();

ObjectId id = ObjectId.get();

如果您想提及父ID,

然后

ObjectId id = new ObjectId("5399aba6e4b0ae375bfdca88");

答案 1 :(得分:0)

要以编程方式创建objectId,请使用以下语法

Map<String,String> objectId = new HashMap<String,String>();
objectId.put("$oid","5399aba6e4b0ae375bfdca88");

然后插入mongodb。