How can I get and return the first element in an array using a Mongo aggregation?
I tried using this code:
db.my_collection.aggregate([ { $project: { resp : { my_field: { $slice: 1 } } }} ])
but I get the following error:
uncaught exception: aggregate failed: { "errmsg" : "exception: invalid operator '$slice'", "code" : 15999, "ok" : 0 }
Note that 'my_field'
is an array of 4 elements, and I only need to return the first element.
aggregate() method always returns Objects no matter what you do and that cannot change. However, that does not mean you cannot put them in an array and return the array in an object.
Valid Operands If the operand resolves to a non-empty array, $first returns the first element in the array: If the operand resolves to an empty array [] , $first does not return a value. If the operand is null or missing, $first returns null.
The aggregation query takes ~80ms while the find query takes 0 or 1ms.
To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.
Since 3.2, we can use $arrayElemAt
to get the first element in an array
db.my_collection.aggregate([ { $project: { resp : { $arrayElemAt: ['$my_field',0] } }} ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With