在嵌套的文档数组中删除嵌入的文档

Mar*_*yen 17 mongodb

我的架构如下所示:

"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"
        }
    ],
Run Code Online (Sandbox Code Playgroud)

我可以用以下方法检索此文档:

db.presentations.find({'content.assets._id': ObjectId('4fc63def5b20fb722900010e')})`
Run Code Online (Sandbox Code Playgroud)

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

db.presentations.update(
  {'content.assets._id': ObjectId('4fc63def5b20fb722900010e')}, 
  {$pull: {'content.assets': {'_id': ObjectId('4fc63def5b20fb722900010e')}}}
)
Run Code Online (Sandbox Code Playgroud)

我正在尝试assets通过其ID 删除相应集合中的项目.有任何想法吗?

Gar*_*ami 29

你真是太近了!请记住,您最外层的"内容"本身就是一个数组.因此,以下2个字符更改工作,使用内容.$.资产内的$ pull值.

db.presentations.update(
  {'content.assets._id': ObjectId('4fc63def5b20fb722900010e')}, 
  {$pull: {'content.$.assets': {'_id': ObjectId('4fc63def5b20fb722900010e')}}}
)
Run Code Online (Sandbox Code Playgroud)

放大.

  • 如果只有一个`content`项包含带有`_id:ObjectId('4fc63def5b20fb722900010e')`的`asset`,这是有效的,因为`$`只匹配第一次出现.知道如何从几个`content.assets`中删除项目?谢谢 (3认同)