0

Can I remove object after ObjectID in MongoDB?

for example we have document:

{
"_id" : ObjectId("5a05f209e479fa45b414d288"),
"name" : "example",
"availability" : null,
"users" : [ 
    ObjectId("59cd1f9a71b8ad5f48eb74f6")
],
"lists" : [ {
        "list" : "example list 2",
        "_id" : ObjectId("5a05f21de479fa45b414d28f"),
        "cards" : [ 
            {
                "name" : "example card 2",
                "_id" : ObjectId("5a05f222e479fa45b414d292"),
                "labels" : [ 
                    {
                        "_id" : ObjectId("5a05f209e479fa45b414d28c"),
                        "label" : {
                        "colour" : "#61BD4F",
                        "name" : "green"
                        }
                    }
                ]
            }
        ]
    }
]
    "__v" : 0

}

Can I delete this object using _id ? for example method in api nodejs findByIdAndRemove to delete only this object ?

                        {
                        "_id" : ObjectId("5a05f209e479fa45b414d28c"),
                        "label" : {
                        "colour" : "#61BD4F",
                        "name" : "green"
                        }
                    }

After this _id ?

                        "_id" : ObjectId("5a05f209e479fa45b414d28c"),

1 Answers1

0

There is no direct way by which you can remove the sub document after objectId in MongoDb.

For this case I achieved the desired result using the code below.

collectionName.update({"lists.cards._id": ObjectId("5a05f222e479fa45b414d292") }, { "$pull": { "lists.0.cards.0.labels": { "_id": ObjectId("5a05f209e479fa45b414d28c") } } });

Using the dot-notation filter the document in the database.

As the query is expected to return only one document I used the zero index to access the desired nested object.