在mongodb中为子阵列设置$ unset不起作用

时间:2013-08-19 05:40:59

标签: mongodb mongoose mongo-java

我有一个表格

的集合
{ 
   "student_id":"123",
   "test": [ { "date_created": "12/3/2013" } ]
}

我想取消设置日期字段。我使用以下查询:

db.student.update({ "student_id" : "1234"} { "$unset" : { "test.$.date_created" : ""}})

我也试过这个:

db.student.update({ "student_id" : "1234"} { "$unset" : { "test.date_created" : ""}})

但是,它不起作用。

1 个答案:

答案 0 :(得分:2)

您应该再次使用 positional operator 查看有关更新的文档。

来自文档:

  

数组字段必须出现在查询参数中,以确定要更新的数组元素。

所以,我们可以通过以下方式获得您想要发生的事情:

db.student.update({ student_id: 123, 'test.date_created': { $exists: true } }, { $unset: { 'test.$.date_created': "" } }

这将取消具有date_created的数组中第一个对象的字段。

如果您知道要删除的数组中date_created字段的位置:

db.student.update({ student_id: 123 }, { $unset: { 'test.0.date_created': "" } }

如果您知道要删除的日期:

db.student.update({ student_id: 123, 'test.date_created': "12/3/2013" }, { $unset: { 'test.$.date_created': "" } }

但是,由于示例中的模式,您将在数组中留下一个空对象...