programing

Java 드라이버를 사용하여 mongoDB에 마지막으로 삽입된 문서의 ID 가져오기

itsource 2022. 10. 14. 21:43
반응형

Java 드라이버를 사용하여 mongoDB에 마지막으로 삽입된 문서의 ID 가져오기

ID를 쉽게 얻을 수 있는 방법이 있습니까(오브젝트Java 드라이버를 사용한 mongoDB 인스턴스의 마지막 삽입 문서 ID)

네가 할 수 있다는 걸 방금 깨달았어

BasicDBObject doc = new BasicDBObject( "name", "Matt" );
collection.insert( doc );
ObjectId id = (ObjectId)doc.get( "_id" );

캐스팅을 피하기 위해Object로.ObjectId(이 경우)com.mongodb.client.MongoCollection collection및 aorg.bson.Document doc다음 작업을 수행할 수 있습니다.

collection.insert(doc);
ObjectId id = doc.getObjectId("_id");

해도 안전하다

doc.set("_id", new ObjectId())

드라이버 코드를 보면

if ( ensureID && id == null ){
    id = ObjectId.get();
    jo.put( "_id" , id );       
}

public static ObjectId get(){
    return new ObjectId();
}

Java 드라이버에 대해서는 모르지만, 나중에 getLastError 명령어를 실행하여 기입의 _id를 취득할 수 있습니다(1.5.4의 경우).

문서를 MongoDB 컬렉션에 삽입한 후 정상적으로 삽입하면 필수 필드(viz. _id)가 업데이트됩니다.삽입된 오브젝트에 _id를 조회할 수 있습니다.

MongoTemplate.class에는 메서드가 있습니다.

protected <T> void doInsert(String collectionName, T objectToSave, MongoWriter<T> writer) {

    assertUpdateableIdIfNotSet(objectToSave);

    initializeVersionProperty(objectToSave);

    maybeEmitEvent(new BeforeConvertEvent<T>(objectToSave, collectionName));

    DBObject dbDoc = toDbObject(objectToSave, writer);

    maybeEmitEvent(new BeforeSaveEvent<T>(objectToSave, dbDoc, collectionName));
    Object id = insertDBObject(collectionName, dbDoc, objectToSave.getClass());

    populateIdIfNecessary(objectToSave, id);
    maybeEmitEvent(new AfterSaveEvent<T>(objectToSave, dbDoc, collectionName));
}

그리고 그 방법은 우리를 위해 ID를 설정할 것이다.

protected void populateIdIfNecessary(Object savedObject, Object id) {

    if (id == null) {
        return;
    }

    if (savedObject instanceof BasicDBObject) {
        DBObject dbObject = (DBObject) savedObject;
        dbObject.put(ID_FIELD, id);
        return;
    }

    MongoPersistentProperty idProp = getIdPropertyFor(savedObject.getClass());

    if (idProp == null) {
        return;
    }

    ConversionService conversionService = mongoConverter.getConversionService();
    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(savedObject.getClass());
    PersistentPropertyAccessor accessor = entity.getPropertyAccessor(savedObject);

    if (accessor.getProperty(idProp) != null) {
        return;
    }

    new ConvertingPropertyAccessor(accessor, conversionService).setProperty(idProp, id);
}

엔티티가 BasicDBobject의 하위 클래스인지 확인할 수 있습니다. 그러면 ID가 설정됩니다.

제 생각에 답은 '아니오'인 것 같아요.

당신이 할 수 있는 것은, 당신이 할 수 있는 것은,_id사용자 자신이 수동으로 또는 구현합니다.CollectibleCodec메카니즘(정확한 의미)BasicBDDocument단, 이러한 솔루션에는 모두 ID 클라이언트 사이드의 생성이 포함됩니다.

그렇다고는 해도, 이 버젼을 생성하는데는 아무런 문제가 없다고 생각합니다._id클라이언트 사이드

삽입 조작은 다음과 같습니다.

DBCollection table1 = db.getCollection("Collection name");
BasicDBObject document = new BasicDBObject();
document.put("_id",value);      
document.put("Name", name);
table1.insert(document);

삽입 후 마지막으로 삽입된 ID:

DBCollection tableDetails = db.getCollection("collection name");
BasicDBObject queryDetails = new BasicDBObject();
queryDetails.put("_id", value);
DBCursor cursorDetails =tableDetails.find(queryDetails);
DBObject oneDetails;
oneDetails=cursorDetails.next();        
String data=oneDetails.get("_id").toString();
System.out.println(data);

값을 inter type으로 변환한 후.

언급URL : https://stackoverflow.com/questions/3338999/get-id-of-last-inserted-document-in-a-mongodb-w-java-driver

반응형