3

I am using spring data mongodb sdk to query mongo db.

The document in mongoDb looks like this:

{
 "data": {
     "suggestions":[
         {
            "key": "take",
             "value": 1

         },
         {
            "key": "donttake",
             "value": 0

         }
      ]
  }  
}

In my api request I have a structure similar to "suggestions" element above. I want to create a query criteria where "is" clause should be the value of "suggestions" element in the api request.

I tried the following code using spring data mongo db:

JsonParser jsonParser = new JsonParser();
ObjectMapper objMapper = new ObjectMapper();
String jsonArrayString = objMapper.writeValueAsString(apirequest.getSuggestions());
JsonArray arrayFromString = jsonParser.parse(jsonArrayString).getAsJsonArray();

criteria = Criteria.where("data.suggestions").is(arrayFromString);

The problem with this code is that when I debug and see the query that gets created using criteria above, I goes in as $java: [{"key": "take", "value": 1}]

Therefore, it can't match it with the mongo document and doesn't fetch me any result.

Is there another way to query and array of documents in mongodb from spring data mongo ?

1 Answer 1

4

I followed a completely different approach by reading some information on querying arrays in mongodb available at

https://docs.mongodb.com/manual/tutorial/query-array-of-documents/

I used elemMatch to solve this problem as follows:

Let's say my API request gets mapped to and object suggestions and keyVal is an object that stores the keyVal pair.

for (KeyVal keyVal: suggestions()){

  Criteria c = 
         Criteria.where("key").is(keyVal.key()).and("value").is(keyVal.value());
  criteria = Criteria.where("data.suggestions").elemMatch(c); 
}

Then criteria can be used in a mongo Query

Also, keep in mind that elemMatch doesn't care about the ordering of elements inside a document in an array. So that way, elemMatch solves the purpose well.

Sign up to request clarification or add additional context in comments.

1 Comment

For anyone looking for a simple example of how to search JSON objects within an array in some outer enclosing key, this Q&A hits the nail on the head +1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.