How to get unique and returning users count from overall user enteries with a user key in couchDB

32 views Asked by At

I have a key called 'username' that stores the user logic records with a unique user id in couchDB. Now I want to get unique users count and returning users count from those records with the help of Map and Reduce functions using the key 'username'.

Here is my current functions:

Map:

function (doc) {
  if(doc.username){
    emit([doc.username],{id: doc.username});
  }
}

Reduce:

function (keys, values, rereduce) {
  if(!rereduce){
    return values;
  }
  var array = [];
  for(var i=0;i<values.length;i++){
    array = array.concat(values[i]);
  }
  var user = {};
  var returning = {};
  for(var j=0;j<array.length;j++){
    if(!user[array[j].id]){
      user[array[j].id] = array[j].con;
    } else if(user[array[j].id] != array[j].con) {
      returning[user[array[j].id]] = 1;
    }
  }
  array[0]['unique'] = Object.keys(user).length;
  array[0]['returning'] = Object.keys(returning).length;
  return array;
}

Output:

{
  "rows": [
    {
      "key": null,
      "value": [
        {
          "id": "user1",
          "unique": 81,
          "returning": 66
        },
        {
          "id": "user2"
        },
        {
          "id": "user3"
        },
        {
          "id": "user4"
        }
      ]
    }
  ]
}

am getting the overall entries details in which instead I want only the count of unique and returning users from the key 'username'.

1

There are 1 answers

0
smathy On

You're doing way too much work here:

map:

function(doc) {
  if(doc.username) {
    emit(doc.username, 1);
  }
}

reduce:

function(keys, values) {
  return sum(values);
}

Then provide the group=true query param when you query the view.