问题
I have document like the following, I want to use map function to get the latest status with given UserId
doc1: _id=id1, UserId='ABC', status='OPEN',...
doc2: _id=id2, UserId='BCD', status='OPEN', .....
doc3: _id=id3, UserId='ABC', status='CLOSED'....
For a given userid, if it related two status: open and close, then return that document with close status document
For a given userid, if it related just open status, then return that document with open status document
doc1: _id=id1, UserId='ABC', status='CLOSED',...
doc2: _id=id2, UserId='BCD', status='OPEN', .....
I am trying do this as following map, if Userid is the same, , return the close status document, but not working,
function(doc) {
var docArr = [];
if (doc.event) {
if(doc.UserId){
docArr.push(doc)
}
}
for (var i=0; i<docArr.length; i++) {
for(var j=0; j<i; j++) {
if (docArr[i].UserId == docArr[j].UserId) {
if (docArr[i].status == "CLOSED")
{
docArr.splice(j,1)
}
else(docArr[j].status == "CLOSED")
{
docArr.splice(i,1)
}
}
}
}
for (var i=0; i<docArr.length; i++) {
emit(docArr[i].UserId,docArr[i]);
}
}
回答1:
If I understand correctly, you are trying to find all documents and their statuses for the same user ID, that's easy with a following map (example not case sensitive):
emit(doc.userId, doc.status)
then the reduce function could deal with finding the right status (your values will be docs of the same user id, with different statuses so you can loop through them finding the one with closed status or returning open if not found).
来源:https://stackoverflow.com/questions/37788566/how-can-get-newest-document-just-using-the-map