2

我正在尝试删除作为文档字段的子属性的数组中的条目。文档的数据如下所示:

{
    _id: 'user1',
    feature: {
        enabled: true,
        history: [
            {
                _id: 'abc123'
                ...
            }
        ]
    },
    ...
}

由于某种原因,我无法使用 $pull 删除该元素,而且我不确定出了什么问题。

我查看了官方文档$pull,这个众所周知的答案,以及这个另一个

我尝试了以下查询

db.getCollection('userData').update({ _id:'user1' }, {
    $pull: {
        'feature.history': { _id: 'abc123' }
    }
})

它没有效果。我已经仔细检查过_id,这是一个正确的匹配。我也尝试过基于相同条目的过滤,认为我需要定位我要删除的数据:

db.getCollection('userData')
    .update({ _id: 'user1', 'feature.history': { _id: 'abc123' }, { ... })

到目前为止没有运气

4

2 回答 2

1

您需要将您的id对象转换为 mongoose ObjectId

db.getCollection('userData').update(
   { "_id": "user1" },
   { "$pull": { "feature.history": { "_id": mongoose.Types.ObjectId(your_id) } }
})
于 2018-07-16T16:49:40.127 回答
0
db.getCollection('userData').update({ _id:'user1', "feature.history._id" : "abc123" }, {
    $pull: {
        'feature.history.$._id': 'abc123'
    }
})
于 2018-07-16T15:34:01.870 回答