MongoDB3.2現(xiàn)在允許將來自多個集合的數(shù)據(jù)通過$查找聚合階段..作為一個實際例子,讓我們假設您有關于書籍的數(shù)據(jù)分成兩個不同的集合。
第一個集合,稱為books
具有以下數(shù)據(jù):
{
"isbn": "978-3-16-148410-0",
"title": "Some cool book",
"author": "John Doe"}{
"isbn": "978-3-16-148999-9",
"title": "Another awesome book",
"author": "Jane Roe"}
和第二個收藏品,叫做books_selling_data
具有以下數(shù)據(jù):
{
"_id": ObjectId("56e31bcf76cdf52e541d9d26"),
"isbn": "978-3-16-148410-0",
"copies_sold": 12500}{
"_id": ObjectId("56e31ce076cdf52e541d9d28"),
"isbn": "978-3-16-148999-9",
"copies_sold": 720050}{
"_id": ObjectId("56e31ce076cdf52e541d9d29"),
"isbn": "978-3-16-148999-9",
"copies_sold": 1000}
要合并這兩個集合,只需通過以下方式使用$lookup:
db.books.aggregate([{
$lookup: {
from: "books_selling_data",
localField: "isbn",
foreignField: "isbn",
as: "copies_sold"
}}])
在此聚合之后,books
集合如下所示:
{
"isbn": "978-3-16-148410-0",
"title": "Some cool book",
"author": "John Doe",
"copies_sold": [
{
"_id": ObjectId("56e31bcf76cdf52e541d9d26"),
"isbn": "978-3-16-148410-0",
"copies_sold": 12500
}
]}{
"isbn": "978-3-16-148999-9",
"title": "Another awesome book",
"author": "Jane Roe",
"copies_sold": [
{
"_id": ObjectId("56e31ce076cdf52e541d9d28"),
"isbn": "978-3-16-148999-9",
"copies_sold": 720050
},
{
"_id": ObjectId("56e31ce076cdf52e541d9d28"),
"isbn": "978-3-16-148999-9",
"copies_sold": 1000
}
]}
重要的是要注意以下幾點:
- “From”集合,在本例中
books_selling_data
無法切分。 - “AS”字段將是一個數(shù)組,如上面的示例所示。
- 中的“l(fā)ocalfield”和“foreign field”選項
$查找階段
如果它們在各自的集合中不存在($查閱文檔
有一個很好的例子)。
因此,作為一個結論,如果您想合并這兩個集合,在本例中有一個平面復制_Sell字段與總副本一起出售,那么您將不得不工作得更多一些,可能使用的是中間集合,然后是$out最后的收藏品