具有聚合功能的MongoDB查询

时间:2018-06-29 17:16:49

标签: mongodb aggregation-framework

我正在使用MongoDB,并且我的收藏集“ book”具有此数据模型:

{
    "_id" : ObjectId("5b32566e2796789e15f18cbe"),
    "service" : ObjectId("5b32550fe66a2c2d781a021e"),
    "state" : "paid",
    "observations" : "",
    "datetime_paid" : "",
    "price" : 50,
    "responsible" : {
        "name" : "Mark",
        "surname" : "Beckam",
        "birthdate" : "",
        "email" : "mark@example.com",
        "phone" : ""
    },
    "updates" : [],
    "tickets" : [ 
        {
            "passenger" : {
                "name" : "Mark",
                "surname" : "Beckam",
                "birthdate" : "",
                "email" : "mark@beckam.com",
                "phone" : "666 666 666"
            },
            "qr_id" : "pwenci3y32m",
            "roundtrip" : "ida_vuelta",
            "price" : 50,
        }
    ]
}

现在,我正在尝试从每本与服务ID匹配的书中查询所有票证和负责人。我的方法是使用聚合:

db.getCollection('books').aggregate([
    { $match: { service: ObjectId("5b32550fe66a2c2d781a021e") } },
    {
      $group: {
        _id: 0,
        tickets: { $push: "$tickets" }
      }
    },
    {
      $project: {
        tickets: {
          $reduce: {
            input: "$tickets",
            initialValue: [],
            in: { $setUnion: ["$$value", "$$this"] }
          }
        }
      }
    }
  ]);

通过该查询,我将返回不同书籍的票证的完整列表,但我还需要每张票证中的负责数据(在每本书中):

{
    "_id" : 0.0,
    "tickets" : [ 
        {
            "passenger" : {
                "name" : "Mark",
                "surname" : "Beckam",
                "birthdate" : "",
                "email" : "mark@beckam.com",
                "phone" : "666 666 666"
            },
            "qr_id" : "",
            "roundtrip" : "ida_vuelta",
            "price" : 50,
            // I need here the responsible field associated to the book that 
               contains that ticket
        }
    ]
}

提前谢谢

1 个答案:

答案 0 :(得分:0)

如何?

db.getCollection('books').aggregate([
    { $match: { service: ObjectId("5b32550fe66a2c2d781a021e") } },
    { $addFields: { "tickets.responsible": "$responsible" } }, // push the responsible information into the "tickets" array
    { $unwind: "$tickets" }, // flatten out all "tickets" to individual documents
    {
      $group: {
        _id: 0,
        tickets: { $addToSet: "$tickets" } // addToSet will eliminate duplicate entries
      }
    }
  ]);