Consider the following collection:
> db.customers.find().pretty();
{
"_id" : ObjectId("5b675d8180db9c13ac5b5c16"),
"name" : "John",
"active": true,
"purchasedItems" : [
{
"item_id" : "5b639e2dbc55ef13a6e50d29",
"quantity" : 2,
"deliveryDate" : 1536095404603
},
{
"item_id" : "5b0f0dcc4d122607cff6ce87",
"quantity" : 33,
"deliveryDate" : 1536179151868
},
{
"item_id" : "5b3a74bd973d5014df9d7d4b",
"quantity" : 23,
"deliveryDate" : 1536265571029
},
{
"item_id" : "5b101be68244dd03fb64acdd",
"quantity" : 111,
"deliveryDate" : 1536351973191
},
{
"item_id" : "5b101be68244dd03fb64acdd",
"quantity" : 11,
"deliveryDate" : 1536092750426
}
]
},
{
"_id" : ObjectId("5b675d8180db9c13ac5b5c16"),
"name" : "John",
"active": true,
"purchasedItems" : [
{
"item_id" : "354639e2dbc55ef13a6e50d29",
"quantity" : 1,
"deliveryDate" : 1536095404603
},
{
"item_id" : "53340dcc4d122607cff6ce87",
"quantity" : 12,
"deliveryDate" : 1536179151868
},
{
"item_id" : "5b7654bd973d5014df9d7d4b",
"quantity" : 44,
"deliveryDate" : 1536265571029
},
{
"item_id" : "5b1014648244dd03fb64acdd",
"quantity" : 14,
"deliveryDate" : 1536351973191
},
{
"item_id" : "5b101be34344dd03fb64acdd",
"quantity" : 6,
"deliveryDate" : 1536092750426
}
]
}
How can I retrieve the nth purchasedItems element in a query without returning the full purchasedItems array ?
I've tried with no sucess (considering index is the array index I want to retrive):
CustomerModel.findOne(
{
_id: customer_id,
active: true
},
{
$arrayElementAt: { purchasedItems: index }
}
)
Error:
Error: error: {
"ok" : 0,
"errmsg" : "Unsupported projection option: $arrayElementAt: { purchasedItems: 1.0 }",
"code" : 2,
"codeName" : "BadValue"
}