4

Having this basic document:

{
  "_id": "userID",
  "name": "User Name",
  "profiles": [
    {
      "level": 1,
      "bar": {
        "_id": "bar1ID",
        "name": "Bar Name"
      }
    },
    {
      "level": 1,
      "bar": {
        "_id": "bar2ID",
        "name": "Bar 2 Name"
      }
    }
  ]
}

I need to remove some fields, and reassign the bar field so that it only contains the _id:

{
  "_id": "userID",
  "profiles": [
    {
      "level": 1,
      "bar": "bar1ID"
    },
    {
      "level": 1,
      "bar": "bar2ID"
    }
  ]
}

Matching with the UserID, and using the mongo aggregation framework

Quarktum
  • 669
  • 1
  • 8
  • 26
  • May help http://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field – G. Ghez Jan 25 '16 at 00:20

1 Answers1

6

Using the .aggregate() method.

The only stage in the pipeline is the $project stage where you use the $map operator.

db.collection.aggregate([
    { "$project": { 
        "profiles": { 
            "$map": { 
                "input": "$profiles", 
                "as": "profile", 
                "in": { 
                    "level": "$$profile.level",
                    "bar": "$$profile.bar._id" 
                } 
            } 
        } 
    } }
])

Which returns:

{
        "_id" : "userID",
        "profiles" : [
                {
                        "level" : 1,
                        "bar" : "bar1ID"
                },
                {
                        "level" : 1,
                        "bar" : "bar2ID"
                }
        ]
}
styvane
  • 59,869
  • 19
  • 150
  • 156