Yoshiya
Yoshiya

Reputation: 452

Query for records that have a certain elements in an array

So I am trying to search for documents that have any of the given tags (i.e. "a", "b", or "c").

The MongoDB query is:

db.my_collection.find({ "tags" : { "$elemMatch" : { "$in" : ["a", "b", "c"] } } })

This works just fine (tags is a document field which is an array of tags for the document). Now the problem is when I try to build this query using SpringData Query and Criteria objects.

List<String> tags = Arrays.asList("a", "b", "c");
Criteria inTags = new Criteria().in(tags);
Criteria where = Criteria.where("tags").elemMatch(inTags);
Query query = new Query(where);
System.out.println(query);

The output of this is:

Query: { "tags" : { "$elemMatch" : { }}}, Fields: null, Sort: null

Which of course does not end up working for me. Does anyone know how to make this work with SpringData query/criteria. I am not interested in ugly work-arounds or using the MongoDB Java driver directly - I can do that. I want to know if there is any way to do this right with the SpringData classes.

Upvotes: 0

Views: 3201

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311855

You're using $elemMatch in a non-standard way here as it's meant to match multiple fields within a single array element. Use a query like this instead:

db.my_collection.find({ "tags": "$in": ["a", "b", "c"] })

That should be easier to get working in SpringData.

Upvotes: 2

Related Questions