【问题标题】:How can I delete a data from nested collection?如何从嵌套集合中删除数据?
【发布时间】:2013-01-20 08:14:45
【问题描述】:

如何删除嵌套集合,例如下图,我想从 Pic 中删除 id 50d3dbce1292dd2e98af1dd2?

数据:

{
    "_id": "50d3dbce1292dd2e98af1dd1",
    "Name": "Bubba",
    "Address": "1111",
    "Pic" : [{"_id": "50d3dbce1292dd2e98af1dd2", "Name": "test1.jpg", "Size":"1000"}, {"_id": "50d3dbce1292dd2e98af1dd3",. "Name": "test2.jpg", "Size":"2000"}],
    "LastModified": {
        "$date": "2012-12-21T03:47:26.535Z"
    }
}

用 $pull 解决:

db.coll.update({}, {$pull: {'things': {'myval': 1}}});

【问题讨论】:

标签: mongodb mongodb-.net-driver


【解决方案1】:

db.collection.update(criteria, objNew, upsert, multi)

db.collection.update( { "_id": "50d3dbce1292dd2e98af1dd1" }, { $unset : { "Pic._id" : 1 } }, false, true);

如果要更新多条记录,请记住将 multi 选项设置为 true。

更新

为了让它发挥作用,我们应该以这种方式改变标准

{ "Pic._id": "50d3dbce1292dd2e98af1dd2" }

或者像 Kev 所说的那样使用$pull:

db.coll.update({}, {$pull: {'things': {'myval': 1}}});

【讨论】:

  • 如果pic 是嵌入文档,这将起作用。题中是数组,这个操作没有效果。
  • 我认为必须使用 $pull 而不是 $unset。让我试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多