14

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.

4

2 回答 2

17

查询数组中的一个元素与查询字段相等性完全相同。您可以在此处阅读 MongoDB 文档。所以您的查询将是:

new Query(Criteria.where("users.$id").is(new ObjectId(userId)))
于 2013-07-18T13:51:36.523 回答
9

在存储库界面中,在方法上键入此查询:

@Query("{'company' :{'$ref' : 'company' , '$id' : ?0}}")
Company find(String companyId);
于 2016-01-05T07:58:17.737 回答