检索每个文档的第二个数组元素 - MongoDB

时间:2016-03-12 22:12:14

标签: mongodb aggregation-framework

我有一个名为bios的MongoDB集合,其中包含与以下类似的文档:

{
        "_id" : ObjectId("51df07b094c6acd67e492f41"),
        "name" : {
                "first" : "John",
                "last" : "McCarthy"
        },
        "birth" : ISODate("1927-09-04T04:00:00Z"),
        "death" : ISODate("2011-12-24T05:00:00Z"),
        "contribs" : [
                "Lisp",
                "Artificial Intelligence",
                "ALGOL"
        ]
},
{
        "_id" : 3,
        "name" : {
                "first" : "Grace",
                "last" : "Hopper"
        },
        "title" : "Rear Admiral",
        "birth" : ISODate("1906-12-09T05:00:00Z"),
        "death" : ISODate("1992-01-01T05:00:00Z"),
        "contribs" : [
                "UNIVAC",
                "compiler",
                "FLOW-MATIC",
                "COBOL"
        ]
}

我的目标是检索bios集合中每个文档的数组contrib的第二个元素。 使用新的聚合管道运算符$filter我运行以下查询:

> db.bios.aggregate([
                     {
                      $match: {"contribs.2":{"$exists":1}}},
                     {
                      $project:{contribs:
                      {
                       $filter:{input:"$contribs", as: "contribs", cond:{}}},_id:0}}])

使用我的查询,输出为:

{ "contribs" : [ "Lisp", "Artificial Intelligence", "ALGOL" ] }
{ "contribs" : [ "UNIVAC", "compiler", "FLOW-MATIC", "COBOL" ] }

这不仅是数组contribs的第二个元素,而是第二个元素存在时contribs数组的投影。

1 个答案:

答案 0 :(得分:4)

你尝试过$ elementAt吗?

db.bios.aggregate([
  { $match: {"contribs.1": { "$exists": 1 } }},
  { $project: { contribs: { $arrayElemAt: [ "$contribs", 1 ] } } }
]);