Shanaka R Shanaka R - 1 year ago 81
Android Question

How to implement "WHERE" condition in Couchbase-lite in Android

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.

Answer Source

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() {
    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.setStartKey(date_time); //to retreive records for a given date_time value
QueryEnumerator result = null;
try {
    result =;    
    for (Iterator<QueryRow> it = result; it.hasNext(); ) {
        QueryRow row =;
        <String, Object> map = row.getDocument().getProperties();
        String employeeName = map.get(QuickstartPreferences.EMPLOYEE_NAME).toString(); // String for Key
        if(employeeName.equalsIgnoreCase(employee_name)) {
            // your logic
} catch (CouchbaseLiteException e) {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download