Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query based on matching elements in DBRef list for mongodb using spring-data-mongodb

I am pretty new to mongodb. I am using spring-data-mongodb for my queries from java. Please guide me if this is achievable.

Say I have two objects "Car" and "User" as following, where car has list of users,

Class Car {

    @Id
    String id;
    String model;
    @DBRef
    List<User> users;
    @DBRef
    Company company;

}

Class User {

    @Id
    String id;
    String name;

}

I want to find all cars for a user, (find all cars where car.users has given user)

Is it possible to achieve using spring-data-mongodb?

It's pretty easy if there was only one DBRef element, eg, for company I can write a query like this,

new Query(Criteria.where("company.$id").is(new ObjectId(companyId)))

But, how to achieve this if there is a list of elements referenced as DBRef??

Thanks for help.

like image 801
shailesh Avatar asked Jul 17 '13 10:07

shailesh


2 Answers

Querying for one element on an array is exactly like query for a field equality. You could read the MongoDB documentation here. So your query will be:

new Query(Criteria.where("users.$id").is(new ObjectId(userId)))
like image 87
Miguel Cartagena Avatar answered Oct 16 '22 20:10

Miguel Cartagena


in repository interface type this query on the method:

@Query("{'company' :{'$ref' : 'company' , '$id' : ?0}}")
Company find(String companyId);
like image 21
hossein ketabi Avatar answered Oct 16 '22 22:10

hossein ketabi