Start a new topic

How to Query rows for fields without a value?

I want to query my data store on a column that I recently added, and therefore not all rows will have a value. I want rows with a specific value OR rows that are empty/null. Just not sure how to model the query, will the empty string represent those value-less rows? null? Thanks in advance.
1 Comment

Hey,



So we expose MongoDb's querying language through our Rest API, for more information check out our REST guide on querying: http://devcenter.kinvey.com/rest/guides/datastore#Querying



Note that you are looking for the "$exists" query, which checks for the existence of a field within an object. This query parameter is not wrapped in the android library, but you can overload the query builder to use it.



GenericJson ex = new GenericJson();

ex.put("$exists", false);



Query q = new Query().equals("myNewField", ex).or(new Query().equals("myNewField", "myValue"));



The query is two parts, with a call to `.or(...)` between them. The first half, `new Query.equals("myNewField", ex)` will create a query where the value of myNewField is equal to the object ex-- in this case, that object is a simple GenericJson which resolved into this: `{"$exists":false}`. So, that first half resolves into something like this: `"myNewField":{"$exists":false}`, which will return any objects where that field doesn't exist.



The second half of the query, within the `or(...)`, is just a simple equals query on myNewField with whatever value you are looking for.



FINAL NOTE: you can use this pattern to overload the query builder for any of the mongo operators that might be not be wrapped by the QueryBuilder class.



Let me know if that helps!
Login or Signup to post a comment