简体   繁体   中英

How to find all documents which their array field contains only two specific values

I did this but it returns all the documents which their authors field contains the two specific values and other values.

Document authors = new Document("authors","firstValue")
    .append("authors", "secondValue");

    MongoCursor<Document> cursor = collection.find(authors).iterator();

    try {
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            System.out.println(doc.get("title")+ " " + doc.get("authors"));
        }
    } 
    finally {
        cursor.close();
    }
    client.close();

I want to find only the documents that contains only these two values.

You are overwriting the values by appending the secondValue to the authors key. So the filter looks like { "authors" : "secondValue" } .

So if you need the documents with array containing only two values including the order you need a filter like { "authors" : [ "firstValue", secondValue" ] }

Document authors = new Document("authors", Arrays.asList("firstValue", "secondValue")) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM