2010-07-26 11 views

risposta

172

odio rispondere alla mia domanda, ma ho appena realizzato si può fare questo:

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

rispondere alla tua domanda è [incoraggiata] (http://stackoverflow.com/help/self-answer), non ti preoccupare. –

+0

Grazie per questo. Sai come fare lo stesso usando i dati di primavera mongodb? –

7

Non so sul driver Java, ma per i posteri, il comando GetLastError può essere eseguito per ottenere il _id di a write, even an upsert (1.5.4)

1

Dopo che un documento è stato inserito nella raccolta MongoDB, l'inserimento riuscito dovrebbe aggiornare i campi richiesti (ad esempio _id). Puoi interrogare l'oggetto inserito per _id.

7

E 'sicuro di fare

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

se si guarda al codice del driver

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

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

intendevi dire "è fatto salvo" o "è sicuro farlo"? – pd40

+1

Per qualche ragione, in MongoDB 2.2.2 (a differenza di prima quando ero su 2.2.0) e con il driver Java 2.10.1, il codice nella risposta non funziona; dopo aver spostato l'oggetto nel documento, non riesco a ottenere il suo _id, anche se MongoDB emette automaticamente automaticamente ObjectId. Tuttavia, la tua soluzione di creare manualmente un ObjectId funziona e grazie per questa opzione! –

+0

BasicDBObject doc = new BasicDBObject("_id", new ObjectId()); System.out.println("doc.id before: " + doc.get("_id")); new Mongo("localhost").getDB("test").getCollection("t").insert(doc); System.out.println("doc.id after: " + doc.get("_id")); questo codice funziona bene per me, testato sulle nuove versioni mongo 2.2.2, driver 2.10.1 – zlob

-2

Si tratta di un'operazione di inserimento:

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

Dopo inserto u ottenere ultimo inserito 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); 

dopo aver ottenuto il valore convertito in tipo inter.

6

per evitare di proiettare Object-ObjectId, dato un com.mongodb.client.MongoCollection collection e org.bson.Document doc, è possibile effettuare le seguenti operazioni:

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

In MongoTemplate.class ha un metodo

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

e il metodo sarà id per noi

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

possiamo vedere se l'entità è una sottoclasse di BasicDBObject, imposterà un id per noi.

Problemi correlati