2016-12-01 56 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/

相關問題