Search code examples
mongodbbson

Mongodb convert object values ​to top level string field


I have the following query mongoDB

{
    "name": "juan",
    "class": {
        "name": "person"  // is the field of another collection.
    }
}

and what I want to achieve is the following

{
    "name": "juan",
    "class": "person"
}

But I need everyone's support to achieve the above.


Solution

  • If all you need is for the data to be returned in the structure you specified, you can use a projection with a find query:

    db.collection.find({}, { name: 1, class: '$class.name' });
    

    Hope this helps.