Getting the first and last element of an array in MongoDB

Mongo DB: I want to make one query to return both the first and last element of an array. I understand that I can do this with several queries, but I would really like to do this with one.

Suppose the collection has a “test”, where each object has an array of “arr” numbers:

 db.test.find({},{arr:{$slice: -1},arr:{$slice: 1}});

This will result in the following:

 { "_id" : ObjectId("xxx"), "arr" : [ 1 ] }    <-- 1 is the first element

Is there a way, possibly an alias for the results? Similar to what the mysql keyword ASwould allow in a query?

+3
source share
1 answer

This is not possible at the moment, but it will be with the Aggregation Framework, which is in development now, if I understand your functional requirements correctly.

, , . , , ?

0

All Articles