Home > Net >  How to exclude nested fields from mongoDB using spring-boot?
How to exclude nested fields from mongoDB using spring-boot?

Time:09-17

I have mongoDB document that looks like this:

[
    {
        "id": 1,
        "name": "abc",
        "class": "top-level",
        "subClass": [
            {
                "id": 1,
                "name": "def",
                "class": "second-level"
            }
        ]
    },
    {
        "id": 2,
        "name": "xyz",
        "class": "top-level",
        "subClass": [
            {
                "id": 1,
                "name": "def",
                "class": "second-level"
            }
        ]
    }
]

I want to exclude the field id from the top-level as well as second-level class. I have tried some query but since I am new to this I can't figure it out. Please help out. Thank you

CodePudding user response:

You just want use the projection option for the query and exclude the none relevant fields, like so:

db.collection.find({},
{
  id: 0,
  "subClass.id": 0
})

Mongo Playground

CodePudding user response:

@Query(value = "{}", fields = "{'id':0, 'subClass.id':0}")

This solved my problem. Thanks for the help

  • Related