title: Java driver: how to get the objectId of an updated object with Mongodb's updateFirst method
body: <p>I'm trying to get the objectId of an object that I have updated - this is my java code using the java driver:</p>
  
  <pre><code>    Query query = new Query();
      query.addCriteria(Criteria.where("color").is("pink"));
      Update update = new Update();
      update.set("name", name);
      WriteResult writeResult = mongoTemplate.updateFirst(query, update, Colors.class);
  
      Log.e("object id", writeResult.getUpsertedId().toString());
  </code></pre>
  
  <p>The log message returns null. I'm using a mongo server 3.0 on mongolab as I'm on the free tier so it shouldn't return null. My mongo shell is also: </p>
  
  <blockquote>
    <p>MongoDB shell version: 3.0.7</p>
  </blockquote>
  
  <p>Is there an easy way to return the  object ID for the doc that I have just updated? What is the point of the method getUpsertedId() if I cannot return the upsertedId?</p>
  
  <p>To do what I want, I currently have to issue two queries which is highly cumbersome:</p>
  
  <pre><code>    //1st query - updating the object first
      Query query = new Query();
      query.addCriteria(Criteria.where("color").is("pink"));
      Update update = new Update();
      update.set("name", name);
      WriteResult writeResult = mongoTemplate.updateFirst(query, update, Colors.class);
      //2nd query - find the object so that I can get its objectid
      Query queryColor = new Query();
      queryColor.addCriteria(Criteria.where("color").is("pink"));
      queryColor.addCriteria(Criteria.where("name").is(name));
      Color color = mongoTemplate.findOne(queryColor, Color.class);
      Log.e("ColorId", color.getId());
  </code></pre>
  
  <p>As per David's answer, I even tried his suggestion to rather use upsert on the template, so I changed the code to the below and it still does not work:</p>
  
  <pre><code>    Query query = new Query();
      query.addCriteria(Criteria.where("color").is("pink"));
      Update update = new Update();
      update.set("name", name);
      WriteResult writeResult = mongoTemplate.upsert(query, update, Colors.class);
  
      Log.e("object id", writeResult.getUpsertedId().toString());
  </code></pre>