MongoDB - 如果对象包含低于x的值,如何删除数组中的对象?

时间:2017-07-29 13:57:23

标签: javascript arrays mongodb meteor mongodb-query

我正在使用Meteor和mongoDB,如果字段“removeTime”低于给定值,我需要从数组中拉出整个对象。

集合“items”中的文档具有以下结构:

{
    "_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。因此,目标是将items-array中的第二个对象删除,但第一个对象保留在doc中:

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

我用$ elemMatch和$ pull尝试了很多方法,但没有任何效果。这就是我现在所拥有的:

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
  }
});
      console.log('pulledOut')
} else {
console.log('letItStayInside')}
}});

我不知道如何删除包含最低值的对象。

1 个答案:

答案 0 :(得分:1)

我认为您的问题可以通过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});

结果是预期的数组,另一个属性可以自己重新分配,我认为不是问题。