是否可以退回两个馆藏的文件?

时间:2016-12-01 00:48:56

标签: mongodb meteor

我想根据员工的类型将员工申诉存储在不同的馆藏中。但我担心我希望能够一次性返回这些不同集合的内容,因为我曾经返回集合的内容,如下面的代码所示:

pendingAppeals = function() {
  return Al.find({status: "Pending"});
}

所以我担心的是,如果我有另一个名为Ml的集合,我是否可以在同一时间内返回AlMl的内容?

2 个答案:

答案 0 :(得分:0)

我不确定您使用的是哪种版本的mongo,而流星是否支持它。但是mongo 3.2有一个聚合类型连接,它根据你的条件从多个集合中获取数据。请参阅:https://docs.mongodb.com/v3.2/reference/operator/aggregation/lookup/

答案 1 :(得分:0)

对您的数据结构不太确定,如果您可以提供一个更容易使用的示例,请参考以下示例,其中我们有studentsteachers集合:< / p>

> db.students.find()
{ "_id" : ObjectId("584020b6410ebb5a4ea03393"), "name" : "bob" }
{ "_id" : ObjectId("584020b6410ebb5a4ea03394"), "name" : "foo" }
{ "_id" : ObjectId("584020b7410ebb5a4ea03395"), "name" : "bill" }

> db.teachers.find().pretty()
{
        "_id" : ObjectId("584020e7410ebb5a4ea03396"),
        "name" : "t 1",
        "studentIds" : [
                ObjectId("584020b6410ebb5a4ea03393"),
                ObjectId("584020b7410ebb5a4ea03395")
        ]
}
{
        "_id" : ObjectId("584020ff410ebb5a4ea03397"),
        "name" : "t 1",
        "studentIds" : [
                ObjectId("584020b6410ebb5a4ea03394"),
                ObjectId("584020b7410ebb5a4ea03395")
        ]
}

然后我们可以将聚合框架与$unwind$lookup阶段一起使用:

db.teachers.aggregate([
    {$unwind: "$studentIds"},
    {$lookup: {
        from: "students",
        localField: "studentIds",
        foreignField: "_id",
        as: "students"
        }
    }
])

我们将获得以下输出:

{
        "_id" : ObjectId("584020e7410ebb5a4ea03396"),
        "name" : "t 1",
        "studentIds" : ObjectId("584020b6410ebb5a4ea03393"),
        "students" : [
                {
                        "_id" : ObjectId("584020b6410ebb5a4ea03393"),
                        "name" : "bob"
                }
        ]
}
{
        "_id" : ObjectId("584020e7410ebb5a4ea03396"),
        "name" : "t 1",
        "studentIds" : ObjectId("584020b7410ebb5a4ea03395"),
        "students" : [
                {
                        "_id" : ObjectId("584020b7410ebb5a4ea03395"),
                        "name" : "bill"
                }
        ]
}
{
        "_id" : ObjectId("584020ff410ebb5a4ea03397"),
        "name" : "t 1",
        "studentIds" : ObjectId("584020b6410ebb5a4ea03394"),
        "students" : [
                {
                        "_id" : ObjectId("584020b6410ebb5a4ea03394"),
                        "name" : "foo"
                }
        ]
}
{
        "_id" : ObjectId("584020ff410ebb5a4ea03397"),
        "name" : "t 1",
        "studentIds" : ObjectId("584020b7410ebb5a4ea03395"),
        "students" : [
                {
                        "_id" : ObjectId("584020b7410ebb5a4ea03395"),
                        "name" : "bill"
                }
        ]
}

参考文献: https://docs.mongodb.com/v3.2/reference/operator/aggregation/ https://docs.mongodb.com/v3.2/reference/operator/aggregation/lookup/