2017-04-02 14 views
1

我有樣本的集合是這樣的:如何檢查是否在數組最後一個元素相匹配的情況下,MongoDB的

{ 
    "_id" : ObjectId("58d6cbc14124691cd8154d72"), 
    "correlativeCode" : "CSLLPA53E20M017W", 
    "registrationMethod" : "taken", 
    "originPlace" : "INSPI", 
    "temperature" : 16, 
    "sampleStatus" : [ 
     { 
      "nameStatus" : "status1", 
      "place" : "place1", 
      "rejectionReason" : "Nothing", 
      "user" : "user1", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     }, 
     { 
      "nameStatus" : "status2", 
      "place" : "place2", 
      "rejectionReason" : "Nothing", 
      "user" : "user4", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     }, 
     { 
      "nameStatus" : "status3", 
      "place" : "place3", 
      "rejectionReason" : "Nothing", 
      "user" : "user3", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     }, 
     { 
      "nameStatus" : "status4", 
      "place" : "place4", 
      "rejectionReason" : "Nothing", 
      "user" : "user1", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     }, 
     { 
      "nameStatus" : "status5", 
      "place" : "place5", 
      "rejectionReason" : "Nothing", 
      "user" : "user5", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     } 
    ] 
} 

首先,我想找到correlativeCode一個樣品(這是很容易)但是..然後 我需要獲取sampleStatus的最後一個元素,並檢查sampleStatus數組的用戶字段是否等於表達式(另一個用戶)。

sampleStatus數組的長度是可變的。

我已經嘗試過$ slice命令,但它不能正常工作。

例如,

如果我找到correlativeCode「CSLLPA53E20M017W」一個樣品,其中最後sampleStatus.user爲user1,應該取0的記錄。

但是,如果我找到一個帶有correlativeCode「CSLLPA53E20M017W」的樣本,其中最後一個sampleStatus.user是user5,它應該獲取1條記錄。

請幫我,我卡住了。

+0

做到這一點'你指的是最新記錄的last'加入sampleStatus,對不對? – thelonglqd

+0

是@thelonglqd,它是最後一個。 –

回答

0

您可以用聚合框架

db.collection.aggregate([ 
    { "$match": { "correlativeCode": "CSLLPA53E20M017W" } }, 
    { "$redact": { 
     "$cond": [ 
      { "$eq": [ 
       { "$let": { 
        "vars": { 
         "item": { "$arrayElemAt": [ "$sampleStatus", -1 ] } 
        }, 
        "in": "$$item.user" 
       } }, 
       "user5" 
      ] }, 
      "$$KEEP", 
      "$$PRUNE" 
     ] 
    }} 
]) 
相關問題