Mongo数据库,SELECT * WHERE id = 3 AND id = 4

时间:2011-07-24 11:38:59

标签: java mongodb mongo-java

我有一个MongoDB,我希望获得两条记录或更多记录并将其放入地图中。 如果我只有一个query.put(ïd", "7");,则下面的代码可以正常工作,但如果我在下面的代码中添加了两个或更多代码,它就无效。

    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"));
    }

如何在地图中获得两条或更多条记录? 对于SQL,等效值为SELCT * FROM Member WHERE id = 7 AND id = 3

如果我可以将列表作为查询给出,那就更完美了,不确定这是否可行。

1 个答案:

答案 0 :(得分:5)

我想你想要$in operator,比如:

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"));
}

...假设值为Integer s。我认为支持数组和BasicDBList实例。