2017-07-29 48 views
0

我使用流星與mongoDB,我需要$從數組中拉出一個完整的對象,如果字段「removeTime」低於給定的值。MongoDB - 如果對象包含的值小於x,如何在數組中刪除對象?

在收集「項目」的文件具有這樣的結構:

{ 
    "_id" : "Guy1", 
    "solvedItems" : { 
     "items" : [ 
      { 
       "itemPush" : "item1-b41f50bc24397735_ABC>14607a25c0864858", 
       "actualTime" : 1501281170509.0, 
       "removeTime" : 3532817170509.0 
      }, 
      { 
       "itemPush" : "item2-691aa30080189962_ABC>14607a25c0864858", 
       "actualTime" : 1501281255771.0, 
       "removeTime" : 1532817255771.0 
      } 
     ] 
    } 
} 

例如給定的值是var givenValue = 2532817255771.0。因此,其目的是使項目陣列中的第二個目的是beeing刪除,但在文檔的第一個停留:

{ 
    "_id" : "Guy1", 
    "solvedItems" : { 
     "items" : [ 
      { 
       "itemPush" : "item1-b41f50bc24397735_ABC>14607a25c0864858", 
       "actualTime" : 1501281170509.0, 
       "removeTime" : 3532817170509.0 
      } 
     ] 
    } 
} 

我試着用$ elemMatch許多方法和$拉,但沒有奏效。這裏是我現在有:

Meteor.methods({ 
    'pullItem': function() { 

//Set the givenValue  
    var givenValue= 2532817255771.0; 

//In case there is an element, which is lower than givenValue, execute  
if(items.findOne({'_id': "Guy1", 'solvedItems.items': {$elemMatch: {'removeTime':{$lt:givenValue}}}})) { 

items.update({'_id': "Guy1"}, { 

    $pull: { 
     'solvedItems.items': //Absolutely no idea how to do it, please help 
    } 
}); 
     console.log('pulledOut') 
} else { 
console.log('letItStayInside')} 
}}); 

我不知道如何刪除包含最低值的對象。

回答

1

我覺得你prolem可以基本過濾器功能的JS陣列上解決

var result = {}; 
var givenValue = 2532817255771.0; 
var tmp = { 
"_id" : "Guy1", 
"solvedItems" : { 
    "items" : [ 
     { 
      "itemPush" : "item1-b41f50bc24397735_ABC>14607a25c0864858", 
      "actualTime" : 1501281170509.0, 
      "removeTime" : 3532817170509.0 
     }, 
     { 
      "itemPush" : "item2-691aa30080189962_ABC>14607a25c0864858", 
      "actualTime" : 1501281255771.0, 
      "removeTime" : 1532817255771.0 
     } 
    ] 
} 
} 

result = tmp.items.filter(function (element){return element.removeTime < givenValue}); 

結果是預期的數組,另一個屬性可以自行重新分配,我認爲這是沒有問題的。

+0

謝謝!你的解決方案很好地獲得所需的對象。然而,我發現了這個簡單的解決方案,它直接操作並拉取匹配的對象:'$ pull:{'solveItems.items':{'removeTime':{$ lt:givenValue}}''。但我認爲你的解決方案也可以工作,對於進一步處理數據非常有用。 – Jaybruh

+0

是的,Mongo有一些內置的查詢來處理這種情況,但是在閱讀這個問題時,我首先想到一個簡單而基本的JS解決方案。 – thelonglqd

相關問題