如何在java中创建mongoDB objectid

2022-09-03 18:37:26

请参阅帖子 如何使用Java将数组添加到MongoDB文档?我已经使用java创建了一个mongo模式,它具有子元素,我正在获取主文档,我想在子元素中也在这里输出外观(我已经标记了我需要的部分_id_id_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代码类似于如何使用Java将数组添加到MongoDB文档中?

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


答案 1

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

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");

答案 2

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

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

然后插入到 mongodb 中。