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

1

1 Answer 1

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"
                }
        ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.