Search code examples
arraysmongodbmongoosesubdocument

Retrieve the first item of an array in a sub-document without getting other sub-documents


In MongoDB - how do you retrieve only the first item of an array which is in a property?

I have a nested document and query it with $text (but that doesn't matter, normal queries don't work either)

The structure of my document:

{
    "_id": ObjectId("...."),
    "propA": {
        "prop1": [
            { ... }, // this is what I want to see
            { ... },
            ...
        ],
        "prop2": { ... },
        "prop3": { ... },
        ...
    },
    "propB": {
        "prop1": { ... }, // +this, but that's not a problem
        "prop2": { ... },
        "prop3": { ... },
        ...
    },
    "propC": { ... },
    ...
}

when I run

collection.find({}, { "propA.prop1": 1, "propB.prop2": 1 });

I get the full array at propA.prop1. When I run instead

collection.find({}, { "propA.prop1": {$slice: 1}, "propB.prop2": 1 });

I get only the first item of propA.prop1 but I get also all the other items inside propA (like propA.prop2, propA.prop3, ...)

I'd want to somehow combine the two queries, but couldn't figure out how (except after retrieving in code).


Solution

  • You can work around this by including a second, non-existent field of propA in your projection:

    collection.find({}, { 
        "propA.prop1": {$slice: 1},
        "propA.nonExistentField": 1,
        "propB.prop2": 1
    });
    

    A bit odd, but it works.