我有两个收藏夹,我想加入他们。 (请以Mongo 3.6语法指导我)。产品:
{
"_id": "5b55c3b303d3a94e0c11e634",
"createdAt": "2018-07-23T12:01:55.760Z",
"updatedAt": "2018-07-23T12:01:55.760Z",
"address": "1111 West Chicago Avenue, Chicago, IL 60642",
"lang": "en",
"poster": "/images/products/poster/pizzzzza.jpg",
"new_price": 45,
"off": 10,
"old_price": 50,
"summary": "10% Cash Back at Pie-Eyed Pizzeria",
"title": "Pie-Eyed Pizzeria",
"status": true,
"category_id": "5b449e6b6f94bb4ab0b67b70"
},
{
"_id": "5b55c34a03d3a94e0c11e631",
"createdAt": "2018-07-23T12:00:10.409Z",
"updatedAt": "2018-07-23T12:00:10.409Z",
"address": "505 N. Lake Shore Dr. Suite #204, Chicago, IL 60611",
"lang": "en",
"poster": "/images/products/poster/asdasd.jpg",
"new_price": 34,
"off": 66,
"old_price": 100,
"summary": "No-Chip Mani-Pedi at MC Lash Studio (Up to 66% Off). Three Options Available.",
"title": "MC Lash Studio",
"status": true,
"category_id": "5b449cf96f94bb4ab0b67b6b"
}
我的第二个集合是ProductDetails:
{
"_id" : ObjectId("5b55c3b703d3a94e0c11e635"),
"createdAt" : ISODate("2018-07-23T16:31:59.323+04:30"),
"updatedAt" : ISODate("2018-07-23T16:31:59.323+04:30"),
"location" : "",
"detail" : "Enter your Detail",
"terms_of_use" : "Enter terms of use",
"description" : "Enter your description",
"product_id" : "5b55c3b303d3a94e0c11e634"
},
{
"_id" : ObjectId("5b55c35003d3a94e0c11e632"),
"createdAt" : ISODate("2018-07-23T16:30:16.368+04:30"),
"updatedAt" : ISODate("2018-07-23T16:30:16.368+04:30"),
"location" : "",
"detail" : "Enter your Detail",
"terms_of_use" : "Enter terms of use",
"description" : "Enter your description",
"product_id" : "5b55c34a03d3a94e0c11e631"
}
我想要在mongodb中这样的东西
select * from Products left join ProductDetails on Products._id = ProductDetails.product_id
我尝试了$ lookup,但是我不知道如何在$ match中放入“ Products._id”。
import Products from '../models/ProductsModel.js';
export function getProductDetail(req, res, next){
Products.aggregate(
{
$lookup:
{
from: "productsdetails",
pipeline: [{$match:{product_id:Products._id}}],
as: "product_detail"
}
})
}
答案 0 :(得分:0)
您需要定义管道阶段,然后将它们传递给聚合函数,如下所示:
import Products from '../models/ProductsModel.js';
export function getProductDetail(req, res, next){
// Pipeline stages definition
const pipeline = [
{ $match: {
"_id" : "5b55c3b303d3a94e0c11e634" // From you request params
}
},
{$lookup: {
from: "ProductDetails",
localField: "_id",
foreignField: "product_id",
as: "details"
}
}
];
Products.aggregate(pipeline).exec()
.then((products) => {
// Handle your response
})
.catch(err => {
next(err);
});
}