Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first element in array and return using Aggregate?

Tags:

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.

like image 261
Alexandre Magro Avatar asked Nov 05 '14 17:11

Alexandre Magro


People also ask

Does aggregate return an array?

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.

How do I fetch the first element of an array in MongoDB?

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.

Is aggregate faster than find?

The aggregation query takes ~80ms while the find query takes 0 or 1ms.

How do I get an element from an array in MongoDB?

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.


1 Answers

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] }     }} ]) 
like image 175
sidgate Avatar answered Oct 26 '22 06:10

sidgate