Mongodb 项目元素位于序号位置

Mongodb 项目元素位于序号位置,mongodb,bson,mongo-shell,Mongodb,Bson,Mongo Shell,我有一个查询,返回第一个元素等于字符串的文档 示例文件: { "_id" : 1, "personal" : { "gender" : "Male", "given_names" : [ "Trent", "Paul" ], "surname" : "James", "date_of_birth" : ISODate("1984-04-28T23:0

我有一个查询,返回第一个元素等于字符串的文档

示例文件:

{
    "_id" : 1,
    "personal" : {
        "gender" : "Male",
        "given_names" : [ 
            "Trent", 
            "Paul"
        ],
        "surname" : "James",
        "date_of_birth" : ISODate("1984-04-28T23:00:00.000Z")
    },
    enrollments: [{
        "start_date" : ISODate("2003-01-29T00:00:00.000Z"),
        "name" : "Psychology",
        "school" : "Humanities",
        "score" : 27
    }] 
}
查询:

db.students.find({
    'personal.given_names.0': 'Trent'
})
我只想投射第一个元素。我已尝试使用
$slice

db.students.find({
    'personal.given_names.0': 'Trent'
}, {
    'personal.given_names': {
        $slice: 1
    }
})
这确实会将数组限制在第一个数组中,但会投影其他所有数组。我还尝试将
1
$slice
操作符传递给投影,但如果
1
似乎总是覆盖
$slice
(无论顺序如何)

我也试着直接提到顺序位置:

'personal.given_names.0': 1
如何仅输出数组的第一个元素?

试试这个

db.students.find({ 
    'personal.given_names': 'Trent'
}, {
    'personal.given_names.$': 1
})//removed ".0" from find

使用聚合框架,您可以执行以下操作:

db.students.aggregate({
    $match: { 'personal.given_names.0': 'Trent' } // find matching documents only
}, {
    $project: {
        '_id': 0, // remove "_id" field from output (and kind of everything else)
        'nameInArray': { $slice: [ '$personal.given_names', 1 ] }, // return only the first element of the array but still as an array
        'nameOnly': { $arrayElemAt: [ '$personal.given_names', 0 ] }// return only the first element of the array
    }
})

我认为这只有在投影一个有序数组位置时才可能,对吗?i、 e.我无法投影
1
2
?$符号表示数组的第0个位置,如果要投影1和2个位置,则无法投影
db.students.aggregate({
    $match: { 'personal.given_names.0': 'Trent' } // find matching documents only
}, {
    $project: {
        '_id': 0, // remove "_id" field from output (and kind of everything else)
        'nameInArray': { $slice: [ '$personal.given_names', 1 ] }, // return only the first element of the array but still as an array
        'nameOnly': { $arrayElemAt: [ '$personal.given_names', 0 ] }// return only the first element of the array
    }
})