仅使用地图如何获取最新文档 [英] How can get newest document just using the map

查看:85
本文介绍了仅使用地图如何获取最新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下文档,我想使用map函数获取给定UserId的最新状态

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'....

对于给定的用户ID,如果它与两个状态有关:打开和关闭,然后返回带有关闭状态文档的文档

For a given userid, if it related two status: open and close, then return that document with close status document

对于给定的用户ID,如果它与打开状态有关,然后返回带有打开状态文档的文档

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', .....

我正在尝试按照以下地图进行操作,如果Userid相同,则返回关闭状态文档,但不起作用,

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]);
   }
}


推荐答案

如果我理解正确,您正在尝试查找同一用户ID的所有文档及其状态,使用以下映射很容易(示例不区分大小写):

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)

然后执行reduce函数可以处理正确的状态(您的值将是具有相同用户ID的文档,但状态不同,因此您可以遍历它们查找具有关闭状态的文档,或者如果找不到则返回打开)。

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).

这篇关于仅使用地图如何获取最新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆