16

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.

Miguel Cartagena
  • 2,576
  • 17
  • 20
shailesh
  • 763
  • 2
  • 9
  • 23

2 Answers2

18

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)))
Miguel Cartagena
  • 2,576
  • 17
  • 20
  • 4
    Hi @Miguel, What if i want to search using user's name instead of user id in single query – Sachin Jul 26 '17 at 19:19
  • been looking for the answer for days now @Sachin. did you find it by any chance? everyone seems to refer to Id, – Hafiz Dec 09 '17 at 21:26
  • @Miguel how to use this with rest api. should I add a new customRepository and use mongoOperation ? – Amir Choubani Mar 13 '18 at 08:13
9

in repository interface type this query on the method:

@Query("{'company' :{'$ref' : 'company' , '$id' : ?0}}")
Company find(String companyId);
hossein ketabi
  • 480
  • 7
  • 19