Search code examples
mongodb-queryspring-data-mongodbspring-mongodbmongotemplate

MongoTemplate invalid projection with conflict path


I am using Spring Data MongoTemplate to query docs. The document stored in the collection is structured as

{
  id: "string", 
  metadata: { -- embeded structure},
  version:  {
              metadata: {
                version: 1,
                --  other fields
              },
              versionContent: { -- embeded structure --}
            }
}

In my query, I only need a subset of fields, so the ProjectionOperation I use is

Aggregation.project("id", "metadata", "version.metadata");

Got the exception:

specification contains two conflicting paths. Cannot specify both 'metadata.version' and 'metadata'

What shall I do to deal with this?


Solution

  • Eventually, instead of specifying fields to include in the projection, I have to specify excluded fields, as below,

    Aggregation.project().andExclude("not-needed-field1", "not-needed-field2")
    

    to avoid the "conflicting paths" exception. Not sure if it is a bug of the MongoTemplate, or there is certain reason to not allow user to include these kind of paths in projection.