1

I'm trying to query the following object from mongodb

[
  {
    "id": "6b3a9814c1990a0578988d9e",
    "details": {
      "buyerId": "5bd450ed0307fa0a3a904376",
      "offerId": "1",
      "productId": "5b3a9814c1880a0578988d6a",
      "productTitle": "Watch",
      "amount": 50,
      "status": "Open",
    }
  }
]

I'm using spring-boot-starter-data-mongodb so first, I tried it the standard way.

Here is what's in my repository,

public interface OfferRepository extends MongoRepository<Offer, String> {

   List<Offer> findOffersByDetailsBuyerId(String buyerId);
}

I've also tried a custom query,

@Query(value = "{'details.buyerId' : ?0 }")
List<Offer> findOfferByDetails_BuyerId(@Param("buyerId") String buyerId);

Both are coming back with an empty array. But if I hard code the buyerId in the query I get the results I want.

Also, when I debug it, I see the param but with double quotes around it? enter image description here

screenshot from mongo compass

enter image description here

Kaigo
  • 1,267
  • 2
  • 14
  • 33

2 Answers2

0

In MongoUI you should check the datatype of field ID. It is ObjectId not String So you need to pass org.bson.types.ObjectId instead of String in the repository method.

 List<Offer> findByDetailsBuyerId(ObjectId buyerId);
Nishant Bhardwaz
  • 924
  • 8
  • 21
  • buyerId is a string, whether it should be or not is another question, but it's actually a string. Thanks – Kaigo Oct 28 '18 at 12:40
  • As mentioned in answer kindly check the datatype of `buyerId` in mongoUI. It should be mongo generated Id, not `String`. Kindly share the screenshot of mognoUI. – Nishant Bhardwaz Oct 28 '18 at 13:08
  • Okay added to the main post. I just tried making it an object id and same result. returns empty array. thanks – Kaigo Oct 28 '18 at 14:25
0

ANSWER

@Query("{ 'details.buyerId' : ?0 }")
List<OfferOverview> findOffersByDetailsBuyerId(String buyerId);

but my main issue was passing the buyerId with double quotes.

Kaigo
  • 1,267
  • 2
  • 14
  • 33