我是no-sql数据库的新手,所以我对这里的子查询有疑问。
让我们想象一下以下结构:
Type (_id, offerId)
Offer (_id, typeId, productId)
Product (_id, subId)
我需要按subId查找所有类型。
我不知道它如何在MongoDB中工作,在SQL中我会做类似的事情:
select * from Type where offerId in
(select _id from Offer where productId in
(select _id from Product where subId = 'test'));
对于MongoDB,我尝试创建某种聚合查询,但是它不起作用:
{
"aggregate": "Type",
"pipeline": [
{
"$lookup": {
"from": "Offer",
"localField": "_id",
"foreignField": "typeId",
"as": "subOffer"
}
},
{
"$lookup": {
"from": "Product",
"localField": "_id",
"foreignField": "subOffer.productId",
"as": "subProduct"
}
},
{
"$match": {
"subProduct.subId": "test"
}
},
{
"$unwind": "$subProduct"
},
{
"$unwind": "$subOffer"
}
]
}
这里有什么建议吗?
答案 0 :(得分:1)
您可以尝试
$lookup
收集offer
$match
类型ID $lookup
收集product
$match
字段subId
和productId
$match
产品不为[]
空$match
的报价不是[]
空的$project
删除要约字段db.type.aggregate([
{
$lookup: {
from: "offer",
let: { tid: "$_id" },
as: "offer",
pipeline: [
{ $match: { $expr: { $eq: ["$$tid", "$typeId"] } } },
{
$lookup: {
from: "product",
as: "product",
let: { pid: "$productId" },
pipeline: [
{
$match: {
$and: [
{ subId: "test" },
{ $expr: { $eq: ["$_id", "$$pid"] } }
]
}
}
]
}
},
{ $match: { product: { $ne: [] } } }
]
}
},
{ $match: { offer: { $ne: [] } } },
{ $project: { offer: 0 } }
])