Search code examples
javascriptnode.jsmongodbprojection

MongoDB hash object projection


If there is an object with unknown keys:

{
  data: {
    someObjectIdStringThatCantBePutInProjection: {
      dontReturn: 123,
      return: 321
    },
    someOtherObjectIdStringThatCantBePutInProjection: {
      dontReturn: 1234,
      return: 4321
    }
  }
}

And I want MongoDB to return only return property of the objects of the objects, what would the projection look like?

For example a projection

{
  data: { **allProperties**: { return: 1 } }
}

should return:

{
  data: {
    someObjectIdStringThatCantBePutInProjection: {
      return: 321
    },
    someOtherObjectIdStringThatCantBePutInProjection: {
      return: 4321
    }
  }
}

Solution

  • Using dynamic values as field names is considered an anti-pattern and introduces unnecessary complexity to queries. Nevertheless, you can convert the data object to an array of k-v tuples by $objectToArray. Use $map to get only the return field you need. Finally, use $arrayToObject to revert back to original form.

    db.collection.aggregate([
      {
        "$set": {
          "data": {
            "$map": {
              "input": {
                "$objectToArray": "$data"
              },
              "as": "d",
              "in": {
                k: "$$d.k",
                v: {
                  return: "$$d.v.return"
                }
              }
            }
          }
        }
      },
      {
        "$set": {
          "data": {
            "$arrayToObject": "$data"
          }
        }
      }
    ])
    

    Mongo Playground