0
votes

Ok i found myself in a simple but annoying problem. My mongo documents are using java.util.Date as id, and as you might guess the id gets converted (spring converters) to ObjectId, I can't update these documents because every time a new ObjectId(Date) is created get a completely different id even though the date is the same...

how do i force mongo to just use java.util.Date as an id?

providing the sample code:

  public void updateNode(...node..) {
    final MongoTemplate mongoTemplate = ...
    final String collectionName = ...
    final Query query = (new Query()).addCriteria(Criteria.where("time").is(node.getTime()));
    final Update update = Update.update("time", node.getTime()).set("top", node.getTop())
          .set("bottom", node.getBottom()).set("mid", node.getMid())
          .set("startTime", node.getStartTime()).set("potential", node.isPotential());

    mongoTemplate.upsert(query, update, MyClassNode.class, collectionName);



  }

if I ran this code for the first time the objects are inserted into the database but with ObjectId... if the node.getTime() is a java.sql.Date then everything is fine.

if the node.getTime() is not a java.sql.Date I cannot update the document if it exists: why? because everytime the document is prepared it creates a new ObjectId the update and query will have two different _id field values and update fails.

1
Can you provide more details like sample code etc.Ananthapadmanabhan

1 Answers

0
votes

On checking the documentation , i found the following details :

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

This also applies to documents inserted through update operations with upsert: true.

The following are common options for storing values for _id:

  • Use an ObjectId.
  • Use a natural unique identifier, if available. This saves space and avoids an additional index.
  • Generate an auto-incrementing number.

What i understood from the documentation was that to avoid inserting the same document more than once, only use upsert: true if the query field is uniquely indexed.So, if this flag is set , you will find your id converted using ObjectId() to make it unique.