带聚合的MongoDB查询

安德烈

我使用的是MongoDB,我的收藏集“ book”有以下数据模型:

{
    "_id" : ObjectId("5b32566e2796789e15f18cbe"),
    "service" : ObjectId("5b32550fe66a2c2d781a021e"),
    "state" : "paid",
    "observations" : "",
    "datetime_paid" : "",
    "price" : 50,
    "responsible" : {
        "name" : "Mark",
        "surname" : "Beckam",
        "birthdate" : "",
        "email" : "[email protected]",
        "phone" : ""
    },
    "updates" : [],
    "tickets" : [ 
        {
            "passenger" : {
                "name" : "Mark",
                "surname" : "Beckam",
                "birthdate" : "",
                "email" : "[email protected]",
                "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" : "[email protected]",
                "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
        }
    ]
}

先感谢您

呆呆的

这个怎么样:

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
      }
    }
  ]);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章