Florentin Hennecker
Florentin Hennecker

Reputation: 2174

Mongodb $project: exclude all but one field of a subdocument, keep the rest

I have documents with the following structure:

{
  field1: 1
  field2: 2
  subdocument: {
    subfield1: 3
    subfield2: 4
    subfield3: 5
    ...
  }
}

I would like to $project (or another operator if $project cannot do that?) so as to get:

  1. all the top-level fields (field1, field2) without having to list them explicitly
  2. only one of the subfields

The expected result would be:

{
  field1: 1
  field2: 2
  subdocument: {
    subfield1: 3
  }
}

I first thought I would look for a way to apply a $project: {subfield1: 0} only on the subdocument but could not find a solution.

Upvotes: 2

Views: 2515

Answers (2)

Valijon
Valijon

Reputation: 13113

@SuleymanSah, 1 step with $mergeObjects

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          "$$ROOT",
          {
            "subdocument": {
              subfield1: "$subdocument.subfield1"
            }
          }
        ]
      }
    }
  }
])

MongoPlayground

Upvotes: 4

SuleymanSah
SuleymanSah

Reputation: 17888

Here is an ugly solution, but does the job.

db.collection.aggregate([
  {
    $addFields: {
      "temp": "$subdocument.subfield1"
    }
  },
  {
    $project: {
      "subdocument": 0
    }
  },
  {
    $addFields: {
      "subdocument.subfield1": "$temp"
    }
  },
  {
    $project: {
      "temp": 0
    }
  }
])

Playground

I am interested a simpler solution.

Upvotes: 1

Related Questions