从特定的父记录中删除子记录

时间:2019-02-17 08:33:58

标签: mongodb

我对mongodb很陌生。我有3个级别的文件。

父级>子级>子级,都具有_id字段。

{
    "_id" : "n2qw5sojs4bajrj",
    "Title" : "Mr",
    "Instance" : "HQ",
    "FirstName" : "ppp",
    "LastName" : "uuuu",
    "Position" : "BF",
    "EmailAddress" : "xxx@ppp.com",
    "Requests" : [ 
        {
            "_id" : "121",
            "Date" : "12/02/2018",
            "Status" : "New",
            "ApprovedBy" : {
                "_id" : "sdfsdf",
                "Name" : "MAN"
            },
            "PPE" : [ 
                {
                    "_id" : "121",
                    "Code" : "PPE",
                    "Status" : "New",
                    "Title" : "Trousers",
                    "Type" : "STD",
                    "Size" : "10111116",
                    "Qty" : 1,
                    "LostDamage" : {
                        "Reason" : "asdaD",
                        "Location" : "Station",
                        "Damage" : "Damged"
                    }
                }, 
                {
                    "_id" : "122",
                    "Code" : "PPEOPP",
                    "Status" : "New",
                    "Title" : "TrousASDASDASDers",
                    "Type" : "STD",
                    "Size" : "10111116",
                    "Qty" : 1,
                    "LostDamage" : {
                        "Reason" : "asdaD",
                        "Location" : "Station",
                        "Damage" : "Damged"
                    }
                }
            ]
        }
    ]
}

我想了解如何通过_id列删除最后一个PPE元素(父>请求> PPE)。

所以我要删除以下孩子:

{
                        "_id" : "121",
                        "Code" : "PPE",
                        "Status" : "New",
                        "Title" : "Trousers",
                        "Type" : "STD",
                        "Size" : "10111116",
                        "Qty" : 1,
                        "LostDamage" : {
                            "Reason" : "asdaD",
                            "Location" : "Station",
                            "Damage" : "Damged"
                        }
                    }

任何提示/帮助都很好。

谢谢 保罗

1 个答案:

答案 0 :(得分:0)

您可以使用MongoDb $ pop从数组中删除最后一个元素。像这样去https://docs.mongodb.com/manual/reference/operator/update/pop/

 db.collection.update({id:1}, { $pop:{ 'request.PPE':1}});