[英]mongoDB join in MERN Stack Project
我有兩個收藏,我想加入他們。 (請以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" } }) }
您需要定義管道階段,然后將它們傳遞給聚合函數,如下所示:
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);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.