从MongoDB中的数组中删除完整行

时间:2015-01-21 00:15:51

标签: mongodb mongodb-query

我在mongoDB集合中有一个文档,其格式如下所示:

数据库集合称为用户

{
    "_id" : ObjectId("54be94e4715beaf4195b89e4"),
    "files" : [ 
        {
            "theName" : "Celtic Statue",
            "fileInfo" : { "size" : 278584,"name" : "celtic.STL" },
            "tags" : [ "statue", "celtic"],
            "updated" : ISODate("2015-01-20T18:15:19.071Z")
        }, 
        {
            "theName" : "Hindu Statue",
            "_id" : ObjectId("54be9b3629e2ae44248c0cfa"),
            "fileInfo" : {"size" : 278584, "name" : "hindu.STL"
            },
            "tags" : [ "decoration",  "hindu"],
            "updated" : ISODate("2015-01-20T18:15:17.071Z")
        }, 
        {
            "theName" : "roman.STL",
            "_id" : ObjectId("54be9b3629e2ae44248c0cfb"),
            "fileInfo" : {"size" : 278584, "name" : "roman.STL"},
            "tags" : [  "statue",  "roman"],
            "updated" : ISODate("2015-01-20T18:15:18.071Z")
        }
    ]
}

我需要删除包含“fileInfo.name ='roman.STL'的整个对象;

这相当于从数组中删除行。

我尝试了很多更新组合,但似乎没有一个能够正常工作。

有谁知道出了什么问题?

以下是我尝试的查询:

1- db.users.findAndModify({query:{"_id":ObjectId("54be9b3629e2ae44248c0cfa")}, sort :{}, update :{$pull : {'files' : { 'fileInfo' : { 'name' : 'roman.STL' } }}}})

2- db.users.update({_id :ObjectId("54be9b3629e2ae44248c0cfa")},{$pull : {'files' : { 'fileInfo' : { 'name' : 'roman.STL'}}}})

3-  db.users.update({"_id" : ObjectId("54be9b3629e2ae44248c0cfa")}, {$pull : {files : { fileInfo :  { $elemMatch : { name : 'roman.STL' } }}}});

4- db.users.update({_id :ObjectId("54be9b3629e2ae44248c0cfa"), 'files.fileInfo.name' : 'roman.STL'},{$pull : {'files' : { 'fileInfo' : { 'name' : 'roman.STL'}}}})

1 个答案:

答案 0 :(得分:2)

试试这个:

db.foo.update(
   {_id :ObjectId("54be94e4715beaf4195b89e4")},
   { $pull : { 'files' : { 'fileInfo.name' : 'roman.STL'}}}
)

结果将是:

{
    "_id" : ObjectId("54be94e4715beaf4195b89e4"),
    "files" : [ 
        {
            "theName" : "Celtic Statue",
            "fileInfo" : {
                "size" : 278584,
                "name" : "celtic.STL"
            },
            "tags" : [ 
                "statue", 
                "celtic"
            ],
            "updated" : ISODate("2015-01-20T18:15:19.071Z")
        }, 
        {
            "theName" : "Hindu Statue",
            "_id" : ObjectId("54be9b3629e2ae44248c0cfa"),
            "fileInfo" : {
                "size" : 278584,
                "name" : "hindu.STL"
            },
            "tags" : [ 
                "decoration", 
                "hindu"
            ],
            "updated" : ISODate("2015-01-20T18:15:17.071Z")
        }
    ]
}