【问题标题】:Retrieve specific index in Mongo array检索 Mongo 数组中的特定索引
【发布时间】:2017-03-14 03:43:40
【问题描述】:

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

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

但它不起作用... 谢谢!

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query


    【解决方案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] }
        }
    }])
    

    在Mongodb $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" }
        }
    }])
    

    【讨论】:

    • 谢谢!它至少仅适用于 MongoDB 3.1 版吗?
    • mongo --version 给我 3.0.8。然后我的技巧出现以下错误: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我错过了什么吗?
    • 我的错,$slice 聚合仅适用于 3.2+,我已经用 3.0 中的解决方案更新了我的帖子
    • 它有效!它不是很快,但完美地解决了我的问题。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 2018-12-04
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    相关资源
    最近更新 更多