Using the aggregation structure in Mongo,
How can I achieve the same result in Mongo <3.2 , as in Mongo 3.2 with the $ arrayElemAt operation ?
Example in Mongo 3.2
Collection
{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
Inquiry
db.users.aggregate([
{
$project:
{
name: 1,
first: { $arrayElemAt: [ "$favorites", 0 ] },
last: { $arrayElemAt: [ "$favorites", -1 ] }
}
}
])
It works great
But I was forced to use Mongo 3.0, so I canβt use this operator, which is perfect for what I want to do
Is there a way to access an array element by index with something like ...
Mongo 3.0
Collection
{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
Inquiry
db.users.aggregate([
{
$project:
{
name: 1,
first: { "$favorites.0" },
last: { "$favorites.1" }
}
}
])
I tried and it does not work, it gives me an empty array.
However, when they are properties, not indexes, it can retrieve values
Any help would be really appreciated.
thank