1

According to the documentation, I'm trying to get a working name for a method of a Spring MongoRepository that have to meet two different conditions. In plain words, the query sounds like: "look up for a determinate object by his id and it is one of mine or I want to share it"

The object:

{
    "_id" : ObjectId("5c497..."),
    "owner" : "myUserId",
    "shared" : false,
}

The query:

db.getCollection('collection').find({$or : [
            { $and : [ { '_id' : ObjectId("5c497...") }, { 'owner' : 'myUserId' } ] },
            { $and : [ { '_id' : ObjectId("5c497...") }, { 'shared' : true } ] }
        ]})

I solved the problem with @Query



@Query("{\$or: [{\$and: [{'_id' : ?0}, {'owner' : ?1}]}, {\$and: [{'_id' : ?0}, {'shared' : true}]} ]}")
fun findIfAvailable(id: ObjectId, owner: String, shared: Boolean = true): Mono<MyObj>


But now, I wondered if it's possible to writing a method name for simplify the code ( and learn how use it ). I tried without success findByIdAndOwnerOrShared, findByIdAndOwnerOrIdAndShared and so on

Thank you

marco
  • 3,193
  • 4
  • 28
  • 51
  • 1
    Looking at the repository query keywords (appendix C in the docs) https://docs.spring.io/spring-data/mongodb/docs/2.1.3.RELEASE/reference/html/#repository-query-keywords have you tried `findBySharedIsTrueOrOwnerEquals(String owner)`? – Mark B Jan 24 '19 at 13:06
  • Since I need the ID, I tried `findBySharedIsTrueOrOwnerEqualsAndIdEquals` but it returns more than one object. I dont get how the boolean expression could be tied together without the use of brackets – marco Jan 24 '19 at 14:09
  • What do you mean you "need the ID"? If you are querying on the ID then just do a `find(id)` since that is always going to return a single item because `id` is unique. I'm confused about what you are trying to do here. – Mark B Jan 24 '19 at 14:12
  • Sorry :-). Maybe it's my wrong logic. I have an ID -> I want the object back **only** if it has my userId associated or if the shared property is true – marco Jan 24 '19 at 14:54
  • I can't think of a way to do that via just the auto-generated queries using the method name. To accomplish that in the repository your use of the `@Query` annotation is probably the best way. I would personally do that logic in the service layer, calling the repository `find(id)` method, and then only returning the object up the chain if it meets your requirements. – Mark B Jan 24 '19 at 14:57
  • Thank you for the support. Indeed, I also thought about your solution; I was only wondering if the query-methods were versatile enough in complex cases. I'll going for `@Query` – marco Jan 24 '19 at 15:14

0 Answers0