I'm trying to use two collections(reviews and products) to find the title and description of products reviewed by reviewer “A”. I just need to display the title and description. Nothing else. So far I have:
db.reviews.aggregate([
{$match: {reviewer : 'A'}},
{$lookup: {
from: "products",
localField: "reviewer",
foreignField: "title",
foreignField: "description",
as: "products_docs"}},
{$project: {
_id: 0,
reviewerID: 1,
title: 1,
description: 1
}}
])
There is supposed to be two products which the current output gives the ID so far but not the title or description.
/* 1 */
{
"reviewerID" : "A"
}
/* 2 */
{
"reviewerID" : "A"
}
Am I missing something?
sample docs :
review :
{
"_id" : ObjectId("5d0b70f2d7367de7f5fa1589"),
"reviewerID" : "A",
"asin" : "1",
"reviewerName" : "Bob",
"helpful" : [
0,
0
],
"reviewText" : "It was really good.",
"overall" : 1.0,
"summary" : "Brilliant",
"unixReviewTime" : 1402185600,
"reviewTime" : "06 8, 2014"
}
product :
{
"_id" : ObjectId("5d0b6d1cd7367de7f58b4906"),
"asin" : "1",
"description" : "Perfect for sunny days",
"title" : "Sunglasses",
"imUrl" : "/sunglasses.jpg",
"related" : {
"also_bought" : [
"729300236X"
]
},
"salesRank" : {
"Shoes" : 257607
},
"categories" : [
[
"Clothing, Shoes & Jewellery",
"Women",
"Accessories",
"Sunglasses & Eyewear Accessories",
"Sunglasses"
],
[
"Clothing, Shoes & Jewellery",
"Men",
"Accessories",
"Sunglasses & Eyewear Accessories",
"Sunglasses"
]
]
}
You can do that using $lookup, Try this below query :
db.review.aggregate([
/** filtering out review coll to get required doc */
{
$match: {
"reviewerID": "A"
}
},
{
$lookup: {
from: "product",
let: {
asin: "$asin" // creating local variable from review Coll's field
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$asin", // foreign field
"$$asin" // local variable created in let
]
}
}
},
/** projecting only required fields from product Coll */
{
$project: {
description: 1,
title: 1,
_id: 0
}
}
],
as: "data"
}
}
])
Test : MongoDB-Playground
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments