Bharadwaja Bapatla
Bharadwaja Bapatla

Reputation: 3363

How to delete particular data in a document in mongodb

Hi the following is my document in mongodb, now i want to delete the data Kumar[] in the given document, I have used (update pop) and remove functions. one is deleting the inside data and the other is deleting the total document any help is appreciated in deleting the required data in document

 {
        "_id" : ObjectId("537d98c2a8357030c4f46cc0"),
        "name" : "karan",
        "address" : "hyd",
        "hobbies" : [ 
            "listeningmusic", 
            "chess"
        ],
        "friends" : [ 
            {
                "satish" : "school"
            }, 
            {
                "naresh" : "college"
            }, 
            {
                "dileep" : "school"
            }, 
            {
                "pavan" : "neighbour"
            }, 
            {
                "kumar" : "office"
            }
        ],
        "kumar" : []
    }

I have tried the following queries

db.userdata.update({kumar:"office"},{$pull:{kumar:"office"}})

 db.userdata.remove({kumar:"office"},1)

Upvotes: 2

Views: 895

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151072

Use the $unset operator, in combination with $exists within the query to match the document with the wrong field:

db.userdata.update({ "kumar": { "$exists": 1 },{ "$unset": { "kumar": "" } })

That will remove the empty array you are showing in the document.

Upvotes: 3

Related Questions