【问题标题】:Remove embedded document in a nested array of documents删除嵌套文档数组中的嵌入文档
【发布时间】:2018-07-24 21:39:06
【问题描述】:

我的架构如下所示:

"content" : [
        {
            "_id" : ObjectId("4fc63de85b20fb72290000f8"),
            "assets" : [
                {
                    "path" : "temp/4f840af9565832fa14000002/4f840b1e565832fa14000007/4fc63de85b20fb72290000f7/content/I_Understanding_and_Measuring.pdf",
                    "_id" : ObjectId("4fc63def5b20fb722900010e")
                },
                {
                    "path" : "temp/4f840af9565832fa14000002/4f840b1e565832fa14000007/4fc63de85b20fb72290000f7/content/me.jpg",
                    "_id" : ObjectId("4fc63e4d5b20fb722900015d")
                }
            ],
            "content" : "",
            "name" : "Downloads"
        },
        {
            "_id" : ObjectId("4fc63dfd5b20fb722900012a"),
            "assets" : [
                {
                    "path" : "temp/4f840af9565832fa14000002/4f840b1e565832fa14000007/4fc63de85b20fb72290000f7/content/me.jpg",
                    "_id" : ObjectId("4fc63e055b20fb7229000147")
                },
                {
                    "path" : "temp/4f840af9565832fa14000002/4f840b1e565832fa14000007/4fc63de85b20fb72290000f7/content/thierry-henry-12-31-11-1.jpg",
                    "_id" : ObjectId("4fc63e525b20fb7229000164")
                }
            ],
            "content" : "",
            "name" : "Bio"
        }
    ],

我可以通过以下方式检索此文档:

db.presentations.find({'content.assets._id': ObjectId('4fc63def5b20fb722900010e')})`

我已尝试以下方法从资产集合中删除文档,并使用以下行,但无济于事:

db.presentations.update(
  {'content.assets._id': ObjectId('4fc63def5b20fb722900010e')}, 
  {$pull: {'content.assets': {'_id': ObjectId('4fc63def5b20fb722900010e')}}}
)

我正在尝试通过其 ID 从相应的 assets 集合中删除一个项目。有什么想法吗?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    你离得太近了!请记住,您最外层的“内容”本身就是一个数组。因此,以下 2 个字符更改有效,在 $pull 的值中使用 content.$.assets

    db.presentations.update(
      {'content.assets._id': ObjectId('4fc63def5b20fb722900010e')}, 
      {$pull: {'content.$.assets': {'_id': ObjectId('4fc63def5b20fb722900010e')}}}
    )
    

    放大。

    【讨论】:

    • 如果只有一个content 项目包含asset_id: ObjectId('4fc63def5b20fb722900010e'),则此方法有效,因为$ 只会匹配第一次出现。知道如何从多个content.assets 中删除该项目吗?谢谢
    • @Cohars 您现在可能已经有了解决方案,但是:要删除多个匹配元素,只需为$pull 提供一个条件。例如$pull: {content: {$elemMatch: { assets.id:ObjectId('4fc63def5b20fb722900010e') }。见docs.mongodb.com/manual/reference/operator/update/pull/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    相关资源
    最近更新 更多