2016-12-01 57 views
0

我想根据其类型将雇员上诉存储在不同的集合中。但恐怕我希望能够马上返回这些不同集合的内容,为我所用返回一个集合的内容显示在下面的代码:是否可以返回两个集合的文档?

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

所以我担心的是,如果我有另一个集合Ml,我可以同时返回和Ml的内容吗?

+0

'Collection.find()'返回*光标*。例如,您可以从发布中返回一个* array *游标。但是,这是一个帮手吗? –

回答

0

不是真的太肯定你的数据结构,如果你能提供这将是容易的工作,但是看看下面的例子,我们有一个studentsteachers集合的例子:

> 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/

相关问题