Home > Net >  How can I get a subfield of dictionary in mongodb?
How can I get a subfield of dictionary in mongodb?

Time:09-16

I've the data structured as follows:

{
    "_id" : ObjectId("61e810b946788906359966"),
    "titles" : {
        "full_name" : "full name",
        "name" : "name"
    },
    "duration" : 161,
    "work_ids" : {
        "plasma_id" : "METRO_3423659",
        "product_code" : "34324000",
      
    }
}

I would like query result as:

{'full_name': 'full name', 'plasma_id': 'METRO_3423659'}

The query that i do is:

 .find({query},{"_id": 0, "work_ids.plasma_id": 1, "titles.full_name": 1}})

but the result i get is 'titles': {'full_name': 'full name'}, 'work_ids': {'plasma_id': 'METRO_3423659'}}

There is any way to get directly the result i want? Thank you very much

CodePudding user response:

Query

  • you can do it using paths, and adding names for the fields

Playmongo

aggregate(
[{"$project": 
   {"_id": 0,
    "full_name": "$titles.full_name",
    "plasma_id": "$work_ids.plasma_id"}}])
  • Related