1

I have recently started working on a Spring Boot project and chose MongoDB as my database. I have the following Document structure.

Following is the User document structure.

@Data
@Builder(setterPrefix = "with")
@Document(collection = "users")
@JsonIgnoreProperties(value = {"password", "createdAt", "updatedAt"}, allowSetters = true)
public class User {

    @Id
    @Indexed
    private String id;

    @Indexed(unique = true, direction = IndexDirection.DESCENDING)
    private String username;

    private String name;

    private String password;

    @CreatedDate
    private Date createdAt;

    @LastModifiedDate
    private Date updatedAt;
}

I have the following structure for Borrow document.

@Document(collection = "borrows")
@Data
@SuperBuilder(setterPrefix = "with")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@AllArgsConstructor
@NoArgsConstructor
public abstract class Borrow {

    @Id
    @EqualsAndHashCode.Include
    private String id;

    @DocumentReference
    private User borrower;

    @DocumentReference
    private User borowee;

    private Date expectedReturnDate;

    private Date actualReturnDate;

    private String place;

    private String occasion;

    private BorrowStatus status;

    public abstract String getType();
}

and two sub classes for Borrow as follows.

BorrowMoney

@Document(collection = "borrows")
@Data
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
@SuperBuilder(setterPrefix = "with")
@BsonDiscriminator(key = "type", value = "Money")
public class BorrowMoney extends Borrow{

    private Double amount;

    @Override
    public String getType() {
        return "Money";
    }
}
@Document(collection = "borrows")
@Data
@SuperBuilder(setterPrefix = "with")
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
@BsonDiscriminator(key = "type", value = "Items")
@AllArgsConstructor
@NoArgsConstructor
public class BorrowItem extends Borrow{

    private String itemName;

    private String description;

    @Override
    public String getType() {
        return "Items";
    }
}

Reminder Document Structure

@Data
@Builder
@Document(collection = "reminders")
public class Reminder {
    @Id
    private String id;

    @DocumentReference
    private Borrow borrow;

    private String message;

    private String header;

    @Indexed
    private String borrower;

    @Indexed
    private String borowee;

    private boolean read;

    @CreatedDate
    private Date createdAt;

    @LastModifiedDate
    private Date updatedAt;
}

I am trying to fetch all the reminders of the currently logged in user by using the id of the user. I followed the official spring-data-mongo documentation for understanding the property expression query.

I wrote the following method in the ReminderRepository.

@Repository
public interface ReminderRepository extends MongoRepository<Reminder, String> {

    List<Reminder> findByBorrowBorrowerId(String id);
}

However, executing this always returns 0 results although the records are already present.

2024-03-30 17:05:26.998 DEBUG 27280 [nio-3080-exec-4,6607f8fe755cc27c4afe5cfe81fb8f8b,75158ed32fd3ebcc] o.s.d.m.c.MongoTemplate : find using query: { "borrow" : { "$oid" : "6605a6ea9796e7405763c9ac"}} fields: Document{{}} for class: class com.kitaab.hisaab.ledger.entity.Reminder in collection: reminders

I am seeing that the above query is getting generated by spring-data-mongo and the id 6605a6ea9796e7405763c9ac here is actually of the user not of the borrow.

As per the documentation it should have taken the property path borrow.borrower.id.

Also tried with @Query("{ 'borrow.borrower.id' : ?0 }}") annotation. However, no breakthrough.

Help me resolve this issue.

Repository link.

Edit 1:

Just the reproducer code

2
  • this approach may help. I tried to use your code in my local but first I needed to start mongo db then I was trying JWT bearer but could not solve. it would be better if you share a small reproducer instead of full code. Commented Apr 2, 2024 at 21:03
  • @ozkanpakdil I have created a new repository which only contains the specific issue. Here is the link. I have tested the approach suggested by you. However, it did not work in this case.
    – nvs87
    Commented Apr 3, 2024 at 15:57

1 Answer 1

1

I am not mongoDB guru but as far as I understand, Spring Data MongoDB does not support querying nested fields(more then 2) directly using the MongoRepository interface. This is due to the way MongoDB handles references between documents.

below code is returning the result

@Service
public class ReminderService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Reminder> getRemindersByUserId(String userId) {
        Query borrowQuery = new Query();
        borrowQuery.addCriteria(Criteria.where("borrower.id").is(userId));
        List<Borrow> borrows = mongoTemplate.find(borrowQuery, Borrow.class);

        List<ObjectId> borrowIds = borrows.stream()
                .map(Borrow::getId)
                .collect(Collectors.toList());

        Query reminderQuery = new Query();
        reminderQuery.addCriteria(Criteria.where("borrow.id").in(borrowIds));
        return mongoTemplate.find(reminderQuery, Reminder.class);
    }
}

But instead you can change the data structure you have, to not to go deep with that inheritance approach and using @DocumentReference just separate all and keep ids. example

public class Reminder {
    @Id
    private ObjectId id;
    private String borrowId;
    private String borrowerId;
    private String borroweeId;
    private String message;
}

this way mongoDB will work faster and MongoRepository will respond as you expected. After all mongodb is a document database not RDBMS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.