简体   繁体   中英

Generated ObjectId for MongoDB

I'd need to generate ObjectId for my entities before I save them to MongoDB . I generate it simply with new org.bson.types.ObjectId() . It creates an object _id which is a quaternion of _time , _machine , _inc and _new . The value of _id itself looks like a normal MongoDB _id . Nevertheless after transforming to JSON and sending it to database, it's saved as an array of four elements. Is there any way how to make it to look like ObjectId generated by MongoDB - "_id" : ObjectId("54edaa41ca190ebda00a2abd") without any text preoprocessing?

This simple Java program works.

MongoClient mongoClient = new MongoClient();
ObjectId objectId = ObjectId.get();
DB test1 = mongoClient.getDB("test1");
BasicDBObject dbObject = new BasicDBObject("_id",objectId)
.append("key", "value");
test1.getCollection("test").insert(dbObject);

Now query with Shell, ObjectId is saved correctly.

> use test1
switched to db test1
> db.test.find()
{ "_id" : ObjectId("55520a15b8a0e51f45921946"), "key" : "value" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM