Search code examples
mongodbmongoosenestedsubdocument

mongodb return just the subdocument by querying the field


I have a structure like this:

{
"_id" : ObjectId("5b155aa3e7179a6034c6dd5b"),
"pinnedKpi" : {
    "Ver01" : [
        "130",
        "138",
        "122",
        "134"
    ],
    "Ver02" : [
        "265",
        "263",
        "142",
        "264"
    ],
    "Ver03" : [ ],
    "Ver04" : [
        "126",
        "134",
        "122",
        "138"
    ]
},
"email" : "john@doe.ca",

Is it possible to do a query like return just the array where email = john@doe.ca and pinnedKpi.Ver01 ---> ["130","138","122","134"]


Solution

  • Just use this:

    db.collection.find({ // find all documents
        "email": "john@doe.ca" // where the "email" field equals some value
    }, {
        "_id": 0, // do not return the "_id" field (included by default)
        "pinnedKpi.Ver01": 1 // only return the "pinnedKpi.Ver01" field
    })