简体   繁体   中英

MongoDb - How to sort and search multiple field in a collection using java

在此处输入图片说明 I am trying to implement a method in which i create a Hashmap of key as string and value as object. Using this hashmap i need to search and sort the collection of data present in Mongo.

Below is id class of mongo db file:

public class Oid{
            String $oid;
            public String get$oid() {
                return $oid;
            }

            public void set$oid(String $oid) {
                this.$oid = $oid;
            }
        }

Below is pojo java file:

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

I am using gson to convert this pojo and while fetching its get converted back to java object.

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

}

in which i send a hashmap of key and its properties for filtering purpose.

Below is the unit test class for testing:

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

In this test class i am expecting to get a list of two records. First record will contain the email value as "berry.sanford@yahoo.com" and second record whose password values is Quo Lux

I would build the query filters and sort orders like below.

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();

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