I want to find all the documents in which a particular key has a same given value. In SQL, this can be implemented using WHERE clause. In Mongo, I can use find(). But I'm not sure how to implement this in Couchbase-lite in Android. It would be great if someone can help to solve this. Thank you.
This is how I solved my problem.
Code for creating and initializing views:
com.couchbase.lite.View dateTimeView = database.getView("dateTimeView");
dateTimeView.setMap(new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
String dateTime = (String) document.get(QuickstartPreferences.DATE_TIME); // String for Key
emitter.emit(dateTime, null);
}
}, "1");
Code for querying the aforementioned view:
Query query = database.getView("dateTimeView").createQuery();
query.setLimit(100);
query.setStartKey(date_time); //to retreive records for a given date_time value
query.setEndKey(date_time);
QueryEnumerator result = null;
try {
result = query.run();
for (Iterator<QueryRow> it = result; it.hasNext(); ) {
QueryRow row = it.next();
<String, Object> map = row.getDocument().getProperties();
String employeeName = map.get(QuickstartPreferences.EMPLOYEE_NAME).toString(); // String for Key
if(employeeName.equalsIgnoreCase(employee_name)) {
// other logic
}
}
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
The important point in here is when you setMap for the view the values of querying field have to be set as the Key
(not as the Value
). The value
could be null
. Then, you can easily use setStartKey
& setEndKey
functions.