如何使用id在mongo中查找三个集合之间的结果

时间:2017-07-29 13:49:18

标签: mongodb

我有三个系列。

用户集合:

{
  "_id" : ObjectId("58a0506767535d5cehjk678"),
  "name" : "someUser",
  "username" : "someUserName"
}

训练:

{ 
  "_id" : ObjectId("5hkhgec28863b500045ff0d6"),
  "location" : "somePlace",
  "coacherId" : "58b9edca8863b500045ff0d0", // userId
  "maxParticipants" : NumberInt(10),
  "time" : ISODate("2017-03-05T17:00:00.000+0000")
}

userOrders:

{
  "_id" : ObjectId("591iuyt602d3ec00049b7c93"),
  "userId" : "5hkhgec28863b500045ff0d6",
  "trainingId" : "5hkhgec28863b500045ff0d6"
}

如何在两个日期之间找到特定用户的所有培训? 在mongo中有一些东西,只有3个查询吗?

1 个答案:

答案 0 :(得分:0)

使用MongoDB的聚合功能和$lookup聚合阶段可能是可以实现的。

这样的事情:

db.userOrders.aggregate(
    [
        {
            $match: {
                "userId" : ObjectId("597c95e3acc4ed0de91a2992") // the id of the user
            }
        },
        {
            $lookup: {
                "from" : "training",
                "localField" : "trainingId",
                "foreignField" : "_id",
                "as" : "training"
            }
        },
        {
            $unwind: {
                path : "$training"
            }
        },
        {
            $match: {
                "training.time" : { $gte: ISODate("2017-03-05T00:00:00.0Z"), $lt: ISODate("2017-03-08T00:00:00.0Z") }
            }
        },
        // if you use MongoDB version >= 3.4
        {
            $replaceRoot: {
                newRoot: "$training"
        }
    }
    ]
);

示例输出文档:

{ 
    "_id" : ObjectId("597c9608acc4ed0de91a2995"), 
    "location" : "somePlace", 
    "coacherId" : "\"Joe\"", 
    "maxParticipants" : NumberInt(10), 
    "time" : ISODate("2017-03-05T17:00:00.000+0000")
}