pp fernandes
pp fernandes

Reputation: 231

How to remove a field from an array using aggregate on MongoDB?

    {Crs:{[
       {Cr: {
            "_id" : ObjectId("5a75baada0f20bd4e612d480"),
            "Number" : 400,
            "Page" : 24,
            "DC" : "NE",
        }},
       {Cr: {
            "_id" : ObjectId("5a75baada0f20bd4e612d489"),
            "Number" : 300,
            "Page" : 14,
            "DC" : "100",
        }},
 ]}}

I have this data that i model using aggregate and I would like to know how can i remove "DC" field from all elements of the array using aggregate.

  >db.crs.aggregate(
    [
        {$group : {_id : null, crs : {$push : {cr : "$$ROOT"}}}},
        {$project : {_id : 0}}
    ]
)

This is what did to model that data. I think its something related with $project.

Upvotes: 3

Views: 3159

Answers (1)

Prashant Pokhriyal
Prashant Pokhriyal

Reputation: 3827

First of all, your document is not a valid JSON schema. You might reconsider the following schema for that particular document.

{
    Crs:[
        {
            "_id" : ObjectId("5a75baada0f20bd4e612d480"),
            "Number" : 400,
            "Page" : 24,
            "DC" : "NE"
        },
        {
            "_id" : ObjectId("5a75baada0f20bd4e612d489"),
            "Number" : 300,
            "Page" : 14,
            "DC" : "100"
        }
    ]
}

Having above schema, you can easily remove DC field using $unset aggregate operator.

db.crs.aggregate([{$unset: 'Crs.DC'}]);

Upvotes: 2

Related Questions