Search code examples
couchdbcloudant

Cloudant/CouchDB query by content of nested array


In my cloudant database I have objects like these. I'd like to query for objects that based on properties in a nested array.

In the example below, how to I query for all objects where there is a vote with userId=="user1"? The query should return both objects. When I search for userId "user2" it should return the first one as the second object only has vote from user1 and user4.

{
    "_id": "1",
    "votes": [
        {
            "userId": "user1",
            "comment": ""
        },
        {
            "userId": "user2",
            "comment": ""
        },
        {
            "userId": "user3",
            "comment": ""
        }
    ]
}

{
    "_id": "2",
    "votes": [
        {
            "userId": "user1",
            "comment": ""
        },
        {
            "userId": "user4",
            "comment": ""
        }
    ]
}

Solution

  • This view will return a list of all votes (where a vote is userId and _id) sorted by userId, to only get user1 use ?key="user1"

    function(doc) {
      for(i in doc.votes)
        emit(doc.votes[i].userId, doc._id);
    }
    

    /dbName/_design/foo/_view/bar?key="user1"

    {"total_rows":5,"offset":0,"rows":[
    {"id":"1","key":"user1","value":"1"},
    {"id":"2","key":"user1","value":"2"}
    ]}