我正在尝试实现一种方法,在该方法中,我创建键的Hashmap(字符串和值作为对象)。使用此哈希图,我需要搜索和排序Mongo中存在的数据集合。
下面是mongo db文件的id类:
public class Oid{
String $oid;
public String get$oid() {
return $oid;
}
public void set$oid(String $oid) {
this.$oid = $oid;
}
}
下面是pojo Java文件:
public class AppUser {
private String password;
private String email;
private Date created_at;
private Date update_at;
Oid _id;
public AppUser() {
super();
// TODO Auto-generated constructor stub
}
public AppUser(String password, String email, Date created_at, Date update_at) {
super();
this.password = password;
this.email = email;
this.created_at = created_at;
this.update_at = update_at;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at(Date created_at) {
this.created_at = created_at;
}
public Date getUpdate_at() {
return update_at;
}
public void setUpdate_at(Date update_at) {
this.update_at = update_at;
}
public Oid get_id() {
return _id;
}
public void set_id(Oid _id) {
this._id = _id;
}
}
我正在使用gson转换此pojo,同时将其转换回java对象。
public class AppUserDao {
public List < AppUser > findMulitple(HashMap < String, Object > map) {
List < AppUser > appUsers = new ArrayList < > ();
MongoDatabase db = getDB();
BasicDBObject query = new BasicDBObject(map.keySet().iterator().next(), map.get(map.keySet().toArray()[0]));
int i = 0;
for (String key: map.keySet()) {
if (i != 0) {
query.append(key, map.get(key));
}
i++;
}
FindIterable < Document > filter = db.getCollection("sampleCollection").find(query);
MongoCursor < Document > cursor = filter.iterator();
try {
String obj = cursor.next().toJson();
System.out.println(obj);
AppUser appUser = gson.fromJson(obj, AppUser.class);
appUsers.add(appUser);
} catch (JsonSyntaxException jse) {
jse.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
cursor.close();
}
return appUsers;
}
}
我在其中发送键的哈希图及其属性以进行过滤。
下面是用于测试的单元测试类:
public class TestAppUser {
public static void main(String args[]) {
HashMap < String, Object > map = new HashMap < > ();
map.put("email", "berry.sanford@yahoo.com");
map.put("password", "Quo Lux");
AppUserDao appUserDao = new AppUserDao();
List < AppUser > appUsers = appUserDao.findMulitple(map);
for (AppUser appUser: appUsers) {
System.out.println(appUser.get_id().get$oid());
}
}
}
在这个测试课程中,我希望获得两个记录的列表。第一个记录的电子邮件值为“ berry.sanford@yahoo.com”,第二个记录的密码为Quo Lux
答案 0 :(得分:2)
我将构建查询过滤器并按如下所示排序顺序。
List<Bson> filters = map.entrySet().stream().map(entry->Filters.eq(entry.getKey(), entry.getValue())).collect(Collectors.toList());
List<Bson> sorts = map.keySet().stream().map(Sorts::ascending).collect(Collectors.toList());
FindIterable<Document> filter = db.getCollection("sampleCollection").find(Filters.and(filters)).sort(Sorts.orderBy(sorts));
MongoCursor<Document> cursor = filter.iterator();