0

I am using Mongo Java Driver, and I am trying to use filters on the collection.find() function. For example, when I have a key which is a java object, the class of which contains certain fields:

Document document = (Document) collection.find(and(
    eq("m_seniority", key.getM_seniority()),
    eq("m_currency",key.getM_currency()),
    eq("m_redCode",key.getM_redCode()),
    eq("m_companyId",key.getM_companyId())
)).first();

I use the above command. But when I want to do that in bulk, I am being passed a collection of keys, ( Collection keys ), I can't access particular variables of the java objects inside as below:

List<Document> docs =  (List<Document>) collection.find(and(
    eq("m_seniority", keys.getM_seniority()),
    eq("m_currency",keys.getM_currency()),
    eq("m_redCode",keys.getM_redCode()),
    eq("m_companyId",keys.getM_companyId())
)).into(new ArrayList<Document>());

Because getters are not of the collection, but just the objects, i can't use getters on the collection. How do I do this?

1
  • Could you provide a sample document? And perhaps flesh out the code around the above blocks? Also, should "key" be "keys" in each of the eq() methods in the second code sample above? i.e. is the second block attempting to be a find call for any key in a given collection of keys? Commented Dec 13, 2017 at 12:06

1 Answer 1

1

To create an or query on all of the Collection keys:

List<Bson> keyFilters = new ArrayList<>();
// for each key create an 'and' filter on seniority, currency, redcode and companyid
for (Key key : keys) {        
    keyFilters.add(
        Filters.and(eq("m_seniority", key.getM_seniority()),
            Filters.eq("m_currency",key.getM_currency()),
            Filters.eq("m_redCode",key.getM_redCode()),
            Filters.eq("m_companyId",key.getM_companyId())
        )
    );
}

List<Document> docs =  (List<Document>) collection.find(
        // 'or' all of the individual key filters
        Filters.or(keyFilters)
).into(new ArrayList<Document>());
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, looks like a great answer. Just one question. When I am iterating on keys, it says Type mismatch between Object and Key, as shown in pasteboard.co/GY7tY9O.png . Can you help with that?
And I can't typecast because it needs an iterable type for iterating as shown in pasteboard.co/GY7At4Z.png
Okay I just added Collection<CurveKeys> (specifying the type in the generic Collection) and it works! Thanks a lot!

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.