0

I have many entities with a big array for each on these entities in DB. I want to retrieve the first and the last element of the array (there is too much data if I get all the arrays). How can I do it ? I tried this:

db.my_collection.findOne({my_query:'is_awesome'}, {'big_array.0':1})

but it doesn't work... Thank's !

1 Answer 1

1

You can use an aggregation instead of findOne, performing a $match.

In Mongodb 3.2, there is $slice in aggregation, so you can $slice the item at position 1 and -1 :

db.my_collection.aggregate([{
    $match: { my_query: 'is_awesome' }
}, {
    $project: {
        my_query: 1,
        firstElement: { $slice: ["$big_array", 1] },
        lastElement: { $slice: ["$big_array", -1] }
    }
}])

In Mongodb < 3.2, $slice cant be used in aggregation, so you can use an $unwind and $group, the following is working in Mongodb 3.0 :

db.my_collection.aggregate([{
    $match: { my_query: 'is_awesome' }
}, {
    $unwind: "$big_array"
}, {
    $group: {
        _id: "$_id",
        my_query: { $first: "$my_query" },
        firstElement: { $first: "$big_array" },
        lastElement: { $last: "$big_array" }
    }
}])
Sign up to request clarification or add additional context in comments.

4 Comments

Thank's ! Is it only available for MongoDB version 3.1 at least ?
mongo --version give me 3.0.8. Then I have the following error with your trick : assert: command failed: { "errmsg" : "exception: invalid operator '$slice'", "code" : 15999, "ok" : 0 } : aggregate failed Error: command failed: { "errmsg" : "exception: invalid operator '$slice'", "code" : 15999, "ok" : 0 } : aggregate failed Did I miss something ?
My bad, $slice in aggregation is only for 3.2+, I've updated my post with a solution working in 3.0
It works ! It's not very fast but solve perfectly my problem. Thank's a lot !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.