I am using Cloudant which is just CouchDB with some more features and I'm looking for the syntax to count the number of elements in an array. Specifically, I'm creating a design document where I only index the document if its field 'color' has more than 0 elements. How do I check to see if there are more than 0 elements in 'color'?
{"_id": "_design/geodd",
"_rev": "5-2729b1453b11f81261ddb3cf3f3de72f",
"st_indexes": {
"geoidx": {
"index": "function(doc) {if (doc.geometry && doc.geometry.coordinates && doc.color != []) {st_index(doc.geometry);}}"
}
}
}
When writing your view, you can execute any Javascript code, so this is more a javascript question than a CouchDB question.
The mistake in your view is that you cannot compare arrays in javascript with the equality operator: doc.color != []
will always return false (because they are not the same objects).
Try replacing this by doc.color.length == 0
if you know in advance that doc.color
is always an array.
If your not sure doc.color
is an array, write isArray(doc.color) && doc.color.length == 0
.
Your view code would become:
{"_id": "_design/geodd",
"_rev": "5-2729b1453b11f81261ddb3cf3f3de72f",
"st_indexes": {
"geoidx": {
"index": "function(doc) {if (doc.geometry && doc.geometry.coordinates && isArray(doc.color) && doc.color.length == 0) {st_index(doc.geometry);}}"
}
}
}