Search code examples
mongodbmongodb-.net-driver

Project in MongoDB removing a level in the document


I have a collection that has documents like this one:

{
  _id: "Id", 
  foo: {
    variable1: {
      value: "value1"
    }, 
    variable2: {
      value: "value2"
    }
  }
}

Where variable can have different values, and I'm trying to get something like this with a mongo query

[
  {
     _id: "Id", 
     values: [
       "value1", "value2" 
     ]
  }
]

Is it possible? I'm not sure if I could do it with an aggregation...


Solution

  • You'll be able to achieve this with a simple aggregation query that projects the object in to an array then re-groups it based on the document id.

    db.test.aggregate([
      { 
         $project: {
            values: { $objectToArray: "$foo" }
         }
      },
      {
         $unwind: "$values",
      },
      {
         $group : { _id: "$_id", values: { $push:  "$values.v.value" } }
      }
    ]);
    
    

    The above will output the following

    { "_id" : "Id", "values" : [ "value1", "value2" ] }
    

    UPDATE:

    As mickl said in the commets you can also use the $map to project the values all within the $project stage.

    db.test.aggregate([
      { 
         $project: {
            values: {
              $map: {
                input: { $objectToArray: "$foo" },
                as: "val",
                in: "$$val.v.value"
              }
            }
         }
      }
    ]);
    

    This will also output

    { "_id" : "Id", "values" : [ "value1", "value2" ] }