I have documents I need to retrieve data from in this format:
{
"id": ObjectId("alskdjflqkjwr23"),
"field1": {
"morefields": values
},
"field2": {
"morefields": values
},
"field3": {
"morefields": values
},
"field14": {
"morefields": values
},
"importantField": {
"subfield1": values,
"subfield2": values,
"importantArray": [
{
"subsubfield1": values,
"importantSubArray": [
{
"subsubsubfield1": values,
"subsubsubfield2": values
},
{
"subsubsubfield1": values,
"subsubsubfield2": values
}
],
"importantValue": values
},
{
"subsubfield1": values,
"subsubfield2": values,
"subsubfield3": values
}
]
}
}
I need the importantValue and elements in the importantSubArray fields, but I can't get my query to return what I need without all of the extra data in the other fields. I just started using Mongo a week ago.
I have tried this query, but only one of the projections works, depending on which order I put them in. So I can either return only the array within importantField, but all 400 or so elements, not just the last 2, or I can return the last 2 elements of importantField.importantArray, but also return all of the other fields, subfields, subsubfields etc.
db.getCollection("my_data").find({},
{
"importantField.importantArray" : 1.0,
"importantField.importantArray": { $slice: -2 }
}
);
How can I get both of these to work at the same time? Thanks.
EDIT:
The expected output should look like this. I need the elements in importantSubArray array and importantValue field
{
"importantSubArray": [
{
"stuff": morestuff
},
],
"importantValue": value
I was able to combine the comment from @prasad_ with a slice by using an aggregation and projecting the fields I want in the first stage and then doing another projection in stage 2 and slicing for the last 2 elements.