Answer a question

In MongoDB documentation they suggest to use ObjecId for manual references. please see https://docs.mongodb.com/manual/reference/database-references/#document-references

original_id = ObjectId()

db.places.insert({
    "_id": original_id,
    "name": "Broadway Center",
    "url": "bc.example.net"
})

db.people.insert({
    "name": "Erin",
    "places_id": original_id,
    "url":  "bc.example.net/Erin"
})

I'm using spring-data-mongodb and what I'm looking for is to have a People class defined like this:

@Document
public class People {

    private String name;
    @Reference // or any Annotation to convert an ObjectId to a String
    private String placesId; 
    private String url;
}

How to have a "places_id" as ObjectId in mongoDB but mapped to a String in our POJO ?

I was expecting to have an annotation like @Reference but it seems to not be implemented.

I don't understand why we don't have this kind of annotation in spring-data-mongodb. I don't want to implement an explicit converter like suggested in spring documentation for all documents that use manual references. Maybe it's not the right approach.

Did I miss something ?

UPDATE :

I like the idea to have a POJO using only String instead of ObjectId. Let's say I've got a class Place like this :

@Document
public class Place {
  @Id
  private String id;
  private String name;
}

place.getId() will be a String but people.getPlaceId() will be an ObjectId. I want to avoid this unnecessary mapping.

Answers

Why don't you leave the field as ObjectId?

@Document
public class People {

    private String name;
    private ObjectId placesId; 
    private String url;
}

If you want to query by this field you can do this:

  • For lists

    List<String> ids // the ids as strings
    List<ObjectId> objIds = ids .stream()
                                .map(i -> new ObjectId(i))
                                .collect(Collectors.toList());
    
  • For single String

    String id // single id
    ObjectId objId = new ObjectId(id);
    
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐