1

I am using Azure Cosmos DB for MongoDB. I have two collections: cars and parkings. A car knows what parking it is in via an @DBRef . I have the following document classes

@Document("cars")
data class CarDocument(

  @Id
  val id: String,

  @DBRef
  val parking: ParkingDocument?
}

@Document("parkings")
data class ParkingDocument(

  @Id
  val id: String

}

And the following spring data repositories:

@Repository
interface CarMongoRepository : MongoRepository<CarDocument, String> {
  fun findByParkingId(id: String): List<CarDocument>
}

@Repository
interface ParkingMongoRepository : MongoRepository<ParkingDocument, String>

When calling findByParkingId('some existent parking id'), it doesn't return any result because the actual filter that spring data sends to CosmosDB for MongoDB is

{
  "parking": {
    "$ref": "parkings",
    "$id": "some existent parking id"
  }
}

I tested this filter in a real MongoDB and it works perfectly: it returns all cars that are parked in that parking. But when running it in CosmosDB for MongoDB, it doesn't match any car. I had to write the filter like this outside of Spring Data (Studio3T) in order to have a match:

{ "parking._id" : "some existent parking id" }

But I can't get Spring Data to build the filter like this. Question: Do you know how to build the filter like this using Spring Data repositories? Or how to make CosmosDB for MongoDB understand the MongoDB's filter?

PS: I tried to delete the @DBRef annotation, but I don't want to store duplicated parkings, because they are very big entities and it would be a nightmare to manage the integrity. Also there is an index in one of it's fields that would be nested as car.parking.code (which I removed from the previous example code to keep it minimal), which isn't allowed in CosmosDB.

Vy Do
  • 46,709
  • 59
  • 215
  • 313
Eduard
  • 191
  • 8

1 Answers1

0

DBRef follows a defined structure in MongoDB. In case you need to move off that by using some other DB maybe also try to use the Spring Data Module built for it. If that's not an option, you can try using @DocumentReference instead of @DBRef to gain more control.

Christoph Strobl
  • 6,491
  • 25
  • 33