Search code examples
javamongodbmongo-java

Mongo Database, SELECT * WHERE id = 3 AND id = 4


I have a MongoDB and I want to get two records or more records and put this in a map. The code below works ok if I have just one query.put(ïd", "7"); but it doesn't work if I put two or more in like in the code below.

    Map<Object,Object> map= new HashMap<Object,Object>();
    DBCollection collection = database.getCollection("Members");
    BasicDBObject query = new BasicDBObject();
    query.put("id", "7");
    query.put("id", "3");
    DBCursor cursor = collection.find(query);
    DBObject one;
    while(cursor.hasNext()) {
        one = cursor.next();
        map.put(one.get("id"),one.get("name"));
    }

How would I get would I get two or more records in the map? For SQL the equivalent would be SELCT * FROM Member WHERE id = 7 AND id = 3

Even more perfect would be if I could give a list as a query, not sure if this is possible.


Solution

  • I think you want the $in operator, something like:

    Map<Object,Object> map= new HashMap<Object,Object>();
    DBCollection collection = database.getCollection("Members");
    BasicDBObject query = new BasicDBObject();
    query.put("id", new BasicDBObject("$in", new Integer[] {3, 7}));
    DBCursor cursor = collection.find(query);
    DBObject one;
    while(cursor.hasNext()) {
        one = cursor.next();
        map.put(one.get("id"),one.get("name"));
    }
    

    ...assuming the values are Integers. I think both arrays and BasicDBList instances are supported.