1

I have a database structure like this:

{
    "_id" : "Foo",
    "registrations" : [ 
        101, 
        102
    ]
}

What I would like to do is create a query that will find all documents that contain a "registrations" array with the value 101 contained within it. I would like to use the QueryBuilder if at all possible because I typically find it easier to use.

Based on this answer, I tried to use elemMatch() to find it, but that didn't seem to have the desired effect:

QueryBuilder.start().put("registrations").elemMatch(new BasicDBObject("_id", 101)).get();

However, the stacktrace said that it is trying to cast the BasicDBObject to an Integer and failing.

java.lang.ClassCastException: java.lang.Integer cannot be cast to com.mongodb.DBObject

So how can I create a query using QueryBuilder that will find all documents that contain a "registrations" array witht he value 101 contained within it?

1 Answer 1

0

After a bit more experimenting, I discovered that what I am wanting is the $in operator, which allows you to check whether or not an array contains particular values. For my specific query, the codeI was looking for was:

QueryBuilder.start().put(registrations).in(Arrays.asList(101)).get();

This returns the DBObject with id "Foo".

If I were looking for more than one registration, I could put them in the list that is the parameter for in().

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

Comments

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.