检索Mongo数组中的特定索引



我有许多实体,每个实体在DB上都有一个大数组。我想检索数组的第一个和最后一个元素(如果获得所有数组,数据就太多了)。我该怎么做呢?我试过了:

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

但它不工作…谢谢的!

您可以使用聚合代替findOne,执行$match

在Mongodb 3.2中,有$slice在聚合,所以你可以$slice在位置1和-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不能在聚合中使用,所以你可以使用$unwind$group,以下是在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" }
    }
}])

最新更新